在单元测试时,需要对被测试方法进行验证:
Mockito提供了verify()方法来验证这个mock实例的某个方法是否被调用,调用了几次,是否带有参数以及带有何种参数等
参考Mockito 如何 mock 返回值为 void 的方法
// 验证方法执行过一次
verify(studentRepository, times(1)).findAll();
//最少调用一次
verify(studentRepository,atLeastOnce()).findAll();
//最多调用一次
verify(studentRepository,atMostOnce()).findAll();
//从没调用过
verify(studentRepository,never()).findAll();
比如需要测试save方法,该方法没有返回值,那么在测试这个方法时,就可以用Mockito.verify()方法来验证
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public void save(StudentEntity studentEntity) {
studentRepository.save(studentEntity);
}
}
src\test\resources\com\example\sutd\service\impl\studentService\testSave\StudentEntity.json
{
"seqId": "DK",
"firstName": "jolin",
"lastName": "li"
}
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
//被测试类
@SpringBootTest(classes = StudentServiceImpl.class)
class StudentServiceImplTest {
@Autowired
private StudentServiceImpl studentService; // 注入被测试类
@MockBean
private StudentRepository studentRepository; // Mock被测试类的依赖
private String jsonPath = "/com/example/sutd/service/impl/studentService/";
@Test
public void testSave() throws IOException {
// data
StudentEntity studentEntity = JsonObjectUtil.parseObjectFromJsonFile(jsonPath + "testSave/StudentEntity.json", StudentEntity.class);
// test
studentService.save(studentEntity);
// verify
Mockito.verify(studentRepository, Mockito.times(1)).save(studentEntity);
}
}