[英]Junit 4 how to initialize in test suite and pass it to test classes
Is there a way in Junit4 to pass some pre-initialized data like http connections that you initialize using say '@ClassRule' in the class annotated with '@RunWith(Suite.class)' to all child (ie suite) test classes? Junit4中是否可以将某些预初始化的数据(例如您使用“ @RunWith(Suite.class)”注释的类中使用“ @ClassRule”初始化的http连接)传递给所有子级(即套件)测试类? Also how to ensure that the classes in the suite cannot be run individually?
另外,如何确保套件中的类不能单独运行?
eg 例如
class A {
private HttpClient client;
@Test
public void someTest() {
client.execute(...);
...
}
}
@RunWith(Suite.class)
@Suite.SuiteClasses({A.class})
public class Suite {
private static HttpClient client;
@ClassRule
public static ExternalResource resource= new ExternalResource() {
@Override
protected void before() throws Throwable {
client = new DefaultHttpClient();
}
}
Thanks, 谢谢,
Paddy 稻田
I don't think that you can achieve that with JUnit. 我认为您无法使用JUnit来实现。
The only possibility I see is to use an abstract class and inherit that one in every test class. 我看到的唯一可能性是使用一个抽象类,并在每个测试类中继承那个抽象类。
public abstract class AbstractTest {
@ClassRule
public static ExternalResource resource= new ExternalResource() {
//...
}
}
public class MyTest extends AbstractTest {
}
Also how to ensure that the classes in the suite cannot be run individually?
另外,如何确保套件中的类不能单独运行?
I don't think that is possible either. 我也不认为这是可能的。
But why would you want that? 但是你为什么要那样? After fixing a single failing test, do you really want to re-run all tests to check if one test is working?
修复单个失败的测试后,您是否真的要重新运行所有测试以检查一项测试是否有效? (Of course, the fix could have introduced side effects but you can re-run all tests when you know that your fixed test is working.) Moreover, the tests should be able to run independently.
(当然,该修复程序可能会带来副作用,但是当您知道固定测试正在运行时,可以重新运行所有测试。)此外,这些测试应该能够独立运行。
When you're using the out-of-the-box Runners
of JUnit you would get any access from a test Suite
to its child tests. 当您使用开箱即用的JUnit
Runners
,您将可以从测试Suite
对其子测试进行任何访问。 Instantiation of the test classes is done internally in the framework. 测试类的实例化在框架内部完成。
If you want to pass information/state from one test to another, I'd suppose to implement some kind of "context". 如果您想将信息/状态从一个测试传递到另一个测试,我想实现某种“上下文”。 Eg a Singleton with a static Getter and Setter for the context that allows your suite to store an
Object
and to read it later on from your tests. 例如,带有上下文的静态Getter和Setter的Singleton ,允许您的套件存储
Object
并在以后的测试中读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.