并行运行junit测试时的竞争条件
我想知道如果我并行运行测试并且两个测试(下面)共享一个实例变量,是否会出现某些竞争状况?因此,我的测试类使用SpringJunit4ClassRunner运行,并且我有2个测试方法a()和b(),变量state
将在每个测试中进行修改或重新分配,并且doSomethingWithState()将使用变量state
并通过它的测试方法.我知道 maven-surefire-plugin 可以在将方法a()和b()都分配给一个线程并并行运行的方法级别上运行它.
I am wondering would it have some race condition if I run my tests in parallel and the two tests (below) share an instance variable? So my test class runs with SpringJunit4ClassRunner, and I have 2 tests method a() and b(), the variable state
will be modified or reassigned from each test, and the doSomethingWithState() would use the variable state
and pass it to the testing method. I know with maven-surefire-plugin you can run it at the method level that both a() and b() will get assigned to a thread and run it in parallel.
@RunWith(SpringJUnit4ClassRunner.class)
public class TestA {
private Object state;
@Test
public void a() {
stateObjectA();
doSomethingWithState();
assertion();
}
@Test
public void b() {
stateObjectB();
doSomethingWithState();
assertion();
}
private void stateObjectA() {
// do some mocking and setup state
}
private void stateObjectB() {
// do some mocking and setup state
}
private void doSomethingWithState() {
// use the state object and feed into the testing method
}
}
我想唯一合理的答案是:取决于 ...取决于您的确切上下文和代码库.
I guess the only reasonable answer is: depends ... on your exact context and code base.
竞争条件的本质是:您有个以上线程来操纵(写入")共享数据.您冗长的问题归结为正是这样的设置.因此,您在上述设置中具有极有潜力的比赛条件.
The essence if race conditions is: you have more than one thread manipulating ("writing") to shared data. Your lengthy question boils down to exactly such a setup. So there is high potential for race conditions in the setup that you described above.
然后:如果您在谈论生产代码中的方法或某些测试框架所调用的方法,则没有任何区别.因为比赛条件不在乎.他们仅关心"多个线程写入共享数据.
And then: it doesn't make any difference if you are talking about methods in production code or methods called by some testing framework. Because race conditions do not care about that. They only "care" about more than one thread writing to shared data.
这就是这里所有的重要内容!
That is all that matters here!