如何对Mockito TestCase进行分组

时间:2019-05-29 11:52:24

标签: mocking junit4 test-suite

我有一些Mockito的测试班。我尝试通过TestSuite聚合它们,但是有错误。

第一个测试用例:

@RunWith(MockitoJUnitRunner.class)
public class GetLastLoginTimeTest {

    @Test
    public void happyScenario_OK() throws Exception{
        ....
    }
    ....
}

第二个测试用例:

@RunWith(MockitoJUnitRunner.class)
public class FetchUserLoginHistoryTest {

    @Test
    public void happyScenario_OK() throws Exception{
        ....
    }
    ....
}

套房测试班:

@RunWith(MockitoJUnitRunner.class)
@SuiteClasses({GetLastLoginTimeTest.class , FetchUserLoginHistoryTest.class})
public class LoginHistoryBLTestSuite {

错误:

org.mockito.exceptions.base.MockitoException: 

No tests found in LoginHistoryBLTestSuite
Is the method annotated with @Test?
Is the method public?

    at org.mockito.internal.runners.RunnerFactory.create(RunnerFactory.java:75)
    at org.mockito.internal.runners.RunnerFactory.createStrict(RunnerFactory.java:40)
    at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:154)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at ....

如果我更改

@RunWith(MockitoJUnitRunner.class)

@RunWith(Suite.class)

然后,由于MullPointerException导致嘲笑期望失败。

1 个答案:

答案 0 :(得分:0)

就像安舒尔在上面的评论中所说:您不应该使用MockitoJunitRunner运行testSuite。

您可以在测试用例上使用RunWith(MockitoJUnitRunner.class)注释,甚至更好的方法是仅使用测试所需的少量静态导入。

一个例子是:

import static org.mockito.Mockito.verify;
(...)

public class ClassUnderTestTest {
  @Rule
  public MockitoRule mockitoRule = MockitoJUnit.rule();

  @Mock
  private ClassToMock mockClassInstance;

  @InjectMocks
  ClassUnderTest classUnderTestInstance;

  @Test
  public void testMethodFunctionality() throws Exception {
    classUnderTestInstance.callFunctionInMock()

    verify(mockClassInstance).calledFunction();
  }

AllTests套件看起来像

@RunWith(Suite.class)
@SuiteClasses({ClassUnderTestTest.class})
public class AllTests {

}