使用Mockito的Annotation简化测试 -- 使用Mockito和JUnit【二】
Mockito有一些非常好用的annotation来简化mock的创建和注入
@Mock
? ?创建一个该类型的mock,可用标注在类,接口上
@InjectMocks该注解标注的对象会自动注入@Mock标注创建的Mock,省去了手工set依赖的过程,非常好用。
?
看看上一篇里的列子
?
@RunWith(MockitoJUnitRunner.class)public class NotifyServiceTest { @InjectMocks private NotifyService notifyService = new NotifyService(); @Mock private UserCenter uc; @Mock private MessageCenter mc; @Test public void testSendMessage() { long userId = 1L; String email = "foo@bar"; when(uc.getUser(userId)).thenReturn(createUserWithEmail(email)); notifyService.sendMessage(userId, "hello"); verify(mc).sendEmail(eq(email), eq("hello")); } private User createUserWithEmail(String email) { User user = new User(); user.setEmail(email); return user; } } ?不再需要手动创建mock和调用set了,简化了代码。
等等,@RunWith(MockitoJUnitRunner.class)是什么?
这是告诉junit使用MockitoJunitRunner来运行该test case,这样才会处理各种注解。
嫌嗦?可用创建一个基类标注上该注解,然后继承它