要测试这段代码:
@Service
public class StudentService {
@Override
public void removeStudentByID(Long studentId) throws StudentExistsException
boolean exists = studentRepo.existsById(studentId);
if (!exists) {
throw new StudentExistsException("Student doesn't exist");
}
studentRepo.deleteById(studentId);
}
}
我们可以像这样模拟/“单元测试”:
package com.example.demo;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class StudenServiceTests { // we only test StudentService, since we (sort of) trust studentRepository (tested it elsewehere/how)
@Mock // A Mock! (alternatively @MockBean)
private StudentRepository studentRepoMock;
@InjectMocks // A real service (with mocks injected;)!!! (alternatively @Autowired/...)
private StudentService testee; // this guy we want to test (to the bone!)
@Test // ..the "good case"
void removeStudentByIdExists() throws StudentExistsException {
// Given:
// we don't even need a student, only his id
// instruct mock for the "first interaction" (see testee code):
when(studentRepoMock.existsById(1L)).thenReturn(true);
// instruct mock for "second interaction" (see testee code):
doNothing().when(studentRepoMock).deleteById(1L); // we could also use ...delete(any(Long.class)) or ..anyLong();
// When: (do it!)
testee.removeStudentByID(1L);
// Then: Verify (interactions, with as exact as possible parameters ..Mockito.any***)
verify(studentRepoMock).existsById(1L); //.times(n) ...when you had a list ;)
verify(studentRepoMock).deleteById(1L);
}
@Test // .. the "bad (but correct) case"/exception
void removeStudentByIdNotExists() throws StudentExistsException {
// Given:
when(studentRepoMock.existsById(1L)).thenReturn(false);
// When:
StudentExistsException thrown = assertThrows(
StudentExistsException.class,
() -> testee.removeStudentByID(1L),
"Expected testee.removeStudentByID to throw, but it didn't");
// Then:
assertNotNull(thrown);
assertTrue(thrown.getMessage().contains("Student doesn't exist"));
}
}
...使用mvn test 运行。
通过这两个测试用例,我们为给定的方法/服务实现了 100% 的测试(和分支)覆盖率。
但不要将其与“集成测试”(我们使用真正的 repo/数据库)混为一谈,那么我们可以使用:
“默认”(假设为空)数据库的示例,已准备好(和@Rollback):
package com.example.demo;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
@SpringBootTest
class StudentServiceIT { // .. here we try to test "all of our application" (as good as possible ..to the bone)
@Autowired //! real "bean", no mock... this is only auxilary for this test, we could use some other method to prepare & verify
private StudentRepository studentRepository;
@Autowired //!! "real service"
private StudentService studentService;
@Test
@Rollback // actually our test is "self-cleaning"...when no exceptions ;)
void removeStudentByIdExists() throws StudentExistsException {
// Given:
Student student = new Student(1L, "Drake", "drake@gmail.com");
studentRepository.save(student);
// When:
studentService.removeStudentByID(1L);
// Then:
assertFalse(studentRepository.findById(1L).isPresent());
}
@Test
@Rollback // in any case (if assumptions were wrong;)
void removeStudentByIdNotExists() throws StudentExistsException {
// Given:
// nothing, we assume "empty db"
// When:
StudentExistsException thrown = assertThrows(
StudentExistsException.class,
() -> studentService.removeStudentByID(1L),
"Expected testee.removeStudentByID to throw, but it didn't");
// Then:
assertNotNull(thrown);
assertTrue(thrown.getMessage().contains("Student doesn't exist"));
}
}
(运行:mvn failsafe:integration-test)
感谢/参考:
Complete Sample@github