Câu trả lời bây giờ là tạo một @ClassRule
trong bộ phần mềm của bạn. Quy tắc sẽ được gọi trước hoặc sau (tùy thuộc vào cách bạn thực hiện nó) mỗi lớp thử nghiệm được chạy. Có một vài lớp cơ sở khác nhau mà bạn có thể mở rộng/triển khai. Điều gì là tốt đẹp về quy tắc lớp học là nếu bạn không thực hiện chúng như là các lớp vô danh thì bạn có thể tái sử dụng mã!
Đây là một bài viết về họ: http://java.dzone.com/articles/junit-49-class-and-suite-level-rules
Dưới đây là một số mẫu mã để minh họa việc sử dụng chúng. Có, nó là tầm thường, nhưng nó sẽ minh họa cho vòng đời đủ tốt để bạn bắt đầu.
Đầu tiên định nghĩa bộ:
import org.junit.*;
import org.junit.rules.ExternalResource;
import org.junit.runners.Suite;
import org.junit.runner.RunWith;
@RunWith(Suite.class)
@Suite.SuiteClasses({
RuleTest.class,
})
public class RuleSuite{
private static int bCount = 0;
private static int aCount = 0;
@ClassRule
public static ExternalResource testRule = new ExternalResource(){
@Override
protected void before() throws Throwable{
System.err.println("before test class: " + ++bCount);
sss = "asdf";
};
@Override
protected void after(){
System.err.println("after test class: " + ++aCount);
};
};
public static String sss;
}
Và bây giờ định nghĩa lớp thử nghiệm:
import static org.junit.Assert.*;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class RuleTest {
@Test
public void asdf1(){
assertNotNull("A value should've been set by a rule.", RuleSuite.sss);
}
@Test
public void asdf2(){
assertEquals("This value should be set by the rule.", "asdf", RuleSuite.sss);
}
}
Tại sao không BeforeSuite và AfterSuite làm việc? – guerda