小编Chr*_*isV的帖子

使用共享模拟进行并行测试

我正在编写一个单元测试类(使用testng),它已经模拟了成员变量(使用Mockito)并且并行运行测试.我最初在@BeforeClass方法中设置了预期的模拟,并且在每个测试用例中,我通过为每个例外情况创建一个Mockito.when来破坏某些东西.

我所看到的(不足为奇)是这些测试不是独立的; Mockito.when在一个测试用例中会影响其他测试用例.我注意到我可以在每次测试之前设置模拟,然后将@BeforeClass更改为@BeforeMethod.我仍然没有想到这些会持续传递,因为测试仍然同时在同一个共享模拟对象上运行.但是,所有测试都开始一致地通过.我的问题是"为什么"?这最终会失败吗?无论我做什么(Thread.sleep等)我都无法重现失败.

使用@BeforeMethod足以使这些测试独立吗?如果是这样,有人可以解释为什么吗

示例代码如下:

public class ExampleTest {
    @Mock
    private List<String> list;

    @BeforeClass // Changing to @BeforeMethod works for some reason
    public void setup() throws NoSuchComponentException, ADPRuntimeException {
        MockitoAnnotations.initMocks(this);
        Mockito.when(list.get(0)).thenReturn("normal");
    }

    @Test
    public void testNormalCase() throws InterruptedException {
        assertEquals(list.get(0), "normal"); // Fails with expected [normal] but found [exceptional]
    }

    @Test
    public void testExceptionalCase() throws InterruptedException {
        Mockito.when(list.get(0)).thenReturn("exceptional");
        assertEquals(list.get(0), "exceptional");
    }
}
Run Code Online (Sandbox Code Playgroud)

concurrency testng unit-testing mocking mockito

2
推荐指数
1
解决办法
1439
查看次数

标签 统计

concurrency ×1

mocking ×1

mockito ×1

testng ×1

unit-testing ×1