文章
问答
冒泡
单元测试框架-mockito初探

对于我们java开发者来说,提到单元测试都会说Junit。确实,Junit是我们用的最多的测试库,但是Junit在面对某些情况的时候,会有点不好搞。比如,你的方法里有依赖外部服务,比如rpc的远程调用,api服务的返回等。而Junit我们更关注结果的返回,而mockito呢,则更多的是在mock数据方面。

今天我们下面简单介绍下mockito

首先我们在pom中引入mockito

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.27.0</version>
    <scope>test</scope>
</dependency>


如果想要配合Junit用的话,需要加入以下的配置

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>2.27.0</version>
    <scope>test</scope>
</dependency>



下面我们来看具体的方法如何使用mockito

看以下代码

@ExtendWith(MockitoExtension.class)

class MockitoServiceImplTest {
    @InjectMocks
    MockitoServiceImpl mockService;

    @Mock
    AServiceImpl aService;
}

  • @ExtendWith 用来初始化一个Mock容器
  • @InjectMocks 即创建一个实例,比如说上面代码的MockitoServiceImpl 他是一个service类,我们针对这个service进行测试,那么我们用@InjectMocks 创建一个实例,这样呢,我们就不需要初始化一个spring的context,这样也就移除了@Autowird
  • @Mock 创建一个依赖的mock对象,比如下文我要在mockService用到aService,那么给aService加上@Mock注解


好了 下面我们进入具体的业务来


比如说我有以下的一个业务,然后我该怎么mock呢

@Service
public class MockitoServiceImpl{

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private CheckService checkService;

    @Override 
    public bool update(Student student){
        Student student = studentDao.findOne(student.getName());
        bool result = checkService.check(student.Id);

        if (result == false){
            return
        }
        try {  
            bool result =  StudentDao.update(student);  
            return result;  
        } catch (Exception e) {  
            throw new RuntimeException("更新失败", e);  
        }  
    }
}





我们来看mockito如何来做

@RunWith(MockitoJUnitRunner.class)
public class MockTest{ 

    @InjectMocks
    private MockitoServiceImpl mockServiceImpl;

    @Mock
    private StudentDao studentDao;

    @Mock
   private CheckService checkService;

    @Test
    public void testInjectMocks() {
       Student student = new Student

       //设置方法的预期返回值
       when(studentDao.findOne("admin")).thenReturn(student);  

        //跳过上面的check方法
        //行为测试 断言的时候不会执行
       verify(checkService, never()).check(anyInt());

       //test method
       bool updateResult =  mockServiceImpl.update(student)

       // 校验结果
       assertEquals(updateResult, true);
    }
}




以上就是一个简单的mockito的使用


关于作者

silen
三流码农
获得点赞
文章被阅读