---
title: "使用Mockito的Annotation简化测试 -- 使用Mockito和JUnit【二】"
author: "jilen"
date: "2012-03-11T21:13:12Z"
tags: []
categories: ["编程语言"]
slug: "mockito-annotation-mockito-junit"
draft: false
lastmod: "2012-03-11T21:47:28Z"
id: 1427368
url: "https://jilen.iteye.com/blog/1427368"
---

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](/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，这样才会处理各种注解。

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