필요성 : 기존에 @InjectMock으로 주입받을 시에는 @Mock이나 @Spy 어노테이션이 붙은 것들만 주입 받게 되었다. 하지만 일반 빈으로 등록된 것들도 주입해야할 때가 있다.
@MockBean & @SpyBean
- Mockito의 Mock 기능을 포함하고 있는 어노테이션으로, 만약 기존에 @Component로 등록된 빈이 있다하더라도 대체하고 목 객체를 새로 추가한다.
- @Autowired 어노테이션이 붙은 필드에도 주입될 수 있다.
- 둘의 차이점은 @Mock과 @Spy와 같다.
장점
- @InjetMock의 한계를 없앤다.
- Mock 객체와 일반 빈을 동일하게 주입할 수 있게 한다.
결론 : @SpringBootTest 환경에서는 @MockBean과 @Autowired를 통해 테스트를 진행하는게 권장된다.
@MockBean, @SpyBean이 Deprecated되었다.
https://hdbstn3055.tistory.com/336을 참고하자
example
@SpringBootTest
@ExtendWith(MockitoExtension.class)
class ApplicationServiceTest {
@Autowired
ApplicationContext context;
@MockBean
ApplicationDao applicationDao;
@Autowired
ApplicationService applicationService;
@Autowired
CollegeStudent collegeStudent;
@Autowired
StudentGrades studentGrades;
@BeforeEach
void setUp() {
collegeStudent.setFirstname("Eric");
collegeStudent.setLastname("Bob");
collegeStudent.setEmailAddress(
collegeStudent.getFirstname() + " " + collegeStudent.getLastname());
collegeStudent.setStudentGrades(studentGrades);
}
@Test
void assertEqualsTestAddGrades() {
Mockito.when(
applicationDao.addGradeResultsForSingleClass(studentGrades.getMathGradeResults()))
.thenReturn(100.0);
double expected = 100.0;
assertEquals(expected,
applicationService.addGradeResultsForSingleClass(
collegeStudent.getStudentGrades().getMathGradeResults()));
Mockito.verify(applicationDao, Mockito.times(1))
.addGradeResultsForSingleClass(studentGrades.getMathGradeResults());
}
}
'Spring Boot > testing' 카테고리의 다른 글
Database Intrgration Testing (0) | 2024.11.12 |
---|---|
Mock을 통한 Throwing Exception (0) | 2024.11.11 |
매개변수화된 테스트 (0) | 2024.11.11 |
TDD(Test-Driven Development) (0) | 2024.11.11 |
조건부 테스트 in JUnit (0) | 2024.11.11 |