Spring/spring_old
03. Test 구성
slow333
2023. 1. 25. 15:37
단위 테스트를 만들면 패키징 시에 test를 진행 후에
1. service에 대한 test 구성
웹 없이 pojo에 대한 시험 구성
service에 대해 di 해야함(자동 생성해서 befor each, after each를 구성)
@SpringBootTest
public class UserServiceLogicTest {
@Autowired // test에서는 이렇게 di 해야함
private UserService userService;
private User kim;
private User lee;
@BeforeEach
public void startUp(){
this.kim = new User("kim", "kim@ac.com");
this.lee = new User("lee", "lee@ac.com");
userService.register(kim);
userService.register(lee);
}
@Test
public void registerTest(){
User sample = User.sample();
// this.userService.register(sample);
assertThat(this.userService.register(sample)).isEqualTo(sample.getId());
assertThat(this.userService.findAll().size()).isEqualTo(3);
this.userService.remove(sample.getId());
}
@Test
public void find(){
assertThat(this.userService.find(lee.getId())).isNotNull();
assertThat(this.userService.find(lee.getId()).getEmail()).isEqualTo(lee.getEmail());
}
@AfterEach
public void cleanUp(){
this.userService.remove(kim.getId());
this.userService.remove(lee.getId());
}
}
2. controller test 구성
web 시험을 위한 annotation 구성 필요
controller에서 자동 생성 방식 사용(setUp, tearDown 자동 생성)
@SpringBootTest
@AutoConfigureMockMvc
//@WebMvcTest(UserController.class) ==> 이 걸로 하면 잘안됨(이유 모름)
register 하는 방식에 대해 좀 복잡함...(이렇게 까지 해야하나 ???)
@SpringBootTest
@AutoConfigureMockMvc
//@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
void register() throws Exception {
User sample = User.sample();
String content = objectMapper.writeValueAsString(sample); // User를 jason으로 변환
mockMvc.perform(post("/users") // 요청을 보냄
.content(content) // content를 보냄
.contentType(MediaType.APPLICATION_JSON) // 타입 지정
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) // 정상이면
.andExpect(content().string(sample.getId()))
.andDo(print()); // 출력
}
// 아래 내용은 어떻게 하는지 모르겠음... 강의에서 안 알려줌
@Test
void find() {
}
@Test
void findAll() {
}
@Test
void modify() {
}
@Test
void remove() {
}
}