티스토리 뷰
단위 테스트 (Unit Test)
1. Controller
@WebMvcTest(PlaceController.class)
//@AutoConfigureMockMvc - MockMvc를 Builder 없이 주입 받을 수 있다.
@Autowired
private MockMvc mvc;
@MockBean
private PlaceService placeService;
@Test
@DisplayName("홈-Place List 가져오기")
void home() throws Exception {
Place p1 = Place.builder().id(1).region("강남구").build();
Place p2 = Place.builder().id(1).region("강남구").build();
List<Place> placeList = new ArrayList<>();
placeList.add(p1);
placeList.add(p2);
//given : Mock 객체가 특정 상황에서 해야하는 행위를 정의하는 메소드
given(placeService.getPlaceList(any())).willReturn(placeList);
//when mvc.perform() : api 테스트 환경을 만들어줌
ResultActions actions = mvc.perform(get("/"));
//then andExpect() : 빌더 구조로 되어있어 .으로 이을 수 있다.
/*
[ RestController일때 ]
actions.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.region").exists(); */
actions.andExpect(model().attribute("region","강남구"))
.andExpect(model().attribute("places", placeList));
.andDo(print());
//verify(placeService).getPlaceList("강남구");
}
2. Service
//1. @SpringBootTest(classes = {ItemService.class} )
//2. @ExtendWith(SpringExtension.class)
//2. @Import({ItemService.class})
//3.
@ExtendWith(MockitoExtension.class)
class ItemServiceTest {
@Mock//@MockBean
private ItemRepository itemRepository;
@InjectMocks//@Autowired
private ItemService itemService;
@Test
void getItem() {
//given
given(itemRepository.findById(1)).willReturn(new Item(1,"아이템1"));
//when
Item item = itemService.getItem(1);
//then
assertEquals(item.getId(),1);
assertEquals(item.getName(),"아이템1");
}
}
3. Repository
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class ItemRepositoryTest {
@Autowired
private ItemRepository itemRepository;
@Test
void findById() {
Item item = itemRepository.findById(2);
assertEquals(item.getPrice(),15000);
}
}
통합 테스트 (Integration Test)
'Spring' 카테고리의 다른 글
Spring Security 시큐리티 필터 이해하기 (0) | 2022.06.13 |
---|---|
Servlet Container 와 Spring Container? Application Context? (0) | 2022.06.13 |
Spring Boot - RestTemplate / Http통신 (0) | 2022.05.31 |
Spring Boot - Validation Check(유효성 검사) (0) | 2022.05.31 |
Spring Boot - Logging(로깅) (0) | 2022.05.31 |