您的位置:首页 > 其它

mockito-初始化注解

2016-05-15 13:51 295 查看
参考:http://site.mockito.org/mockito/docs/current/org/mockito/junit/MockitoRule.html

如果想使用@Mock, @Spy, @InjectMocks等注解时,需要进行初始化后才能使用。

初始化的方法有3种:

1,在Junit的类上面使用@RunWith(MockitoJUnitRunner.class)注解。

但如果你使用的是Spring的话,可能你会使用Spring的测试类(@RunWith(SpringJUnit4ClassRunner.class))

这样的话,你就没有办法使用上面的@RunWith(SpringJUnit4ClassRunner.class)。你还可以使用下面的方法。

2,在测试方法被调用之前,使用MockitoAnnotations.initMocks(this);。例如:

@Before

public void initMocks(){

MockitoAnnotations.initMocks(this);

}

@Before保证了在被测试的方法被调用之前,调用@Before所注解的方法

这个方法还有下面的好处。(具体是什么样子还没有试过)

Allows shorthand creation of objects required for testing.

Minimizes repetitive mock creation code.

Makes the test class more readable.

Makes the verification error easier to read because field name is used to identify the mock.

3,使用MockitoRule。如下:

@Rule

public MockitoRule rule = MockitoJUnit.rule();

这个方法会调用validateMockitoUsage方法。这个方法有一些好处,具体什么好处还不太清楚。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: