使用Mockito的Annotation简化测试 -- 使用Mockito和JUnit【二】

Mockito有一些非常好用的annotation来简化mock的创建和注入

@Mock

   创建一个该类型的mock,可用标注在类,接口上

@InjectMocks该注解标注的对象会自动注入@Mock标注创建的Mock,省去了手工set依赖的过程,非常好用。

 

看看上一篇里的列子

 

public class NotifyService {  
    private UserCenter uc;  
    private MessageCenter mc;  
  
    public void sendMessage(long userId, String message) {  
        String email = uc.getUser(userId).getEmail();  
        mc.sendEmail(email, message);  
    }  
  
    public void setUc(UserCenter uc) {  
        this.uc = uc;  
    }  
  
    public void setMc(MessageCenter mc) {  
        this.mc = mc;  
    }  
}  

 

 这是我们需要测试的类

 

如果不用注解,我们的单元测试需要手工创建mock并注入到被测试的对象中。就像前一篇http://jilen.iteye.com/blog/1384898中的单元测试

 

public class NotifyServiceTest {  
    private NotifyService notifyService;  
    private UserCenter uc;  
    private MessageCenter mc;  
  
    @Before  
    public void setUp() {  
        notifyService = new NotifyService();  
        uc = mock(UserCenter.class);  
        mc = mock(MessageCenter.class);  
        notifyService.setUc(uc);  
        notifyService.setMc(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;  
    }  
  
}  

 setUp方法中mock,并注入依赖

 

使用注解之后可用简化为

 

@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,这样才会处理各种注解。

嫌啰嗦?可用创建一个基类标注上该注解,然后继承它

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值