## 참고 : test 패키지 구조
![[0. ChatGPT 프록시 서버 소개 및 주요 서비스#test 패키지 구조]]
## `config` 작성
```java
@TestConfiguration
public class ValidationAndExceptionTestConfig {
@Bean
public PromptTemplateRequest idNull(){
return PromptTemplateRequest.builder()
.content("idNull")
.build();
}
@Bean
public PromptTemplateRequest contentNull(){
return PromptTemplateRequest.builder()
.id("contentNull")
.build();
}
@Bean
public PromptTemplateRequest templateRequest(){
return PromptTemplateRequest.builder()
.id("example")
.content("Say '${word1} is ${word2}!'. Only say answer. Do not say anything else.")
.build();
}
@Bean
public Map<String, String> map(){
Map<String, String> map = new HashMap<>();
map.put("poo", "poo poo-!");
return map;
}
}
```
## `ValidationAndExceptionTest` 작성
### 클래스 생성
```java
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@TestPropertySource(locations = "classpath:test.properties")
@Import(ValidationAndExceptionTestConfig.class)
public class ValidationAndExceptionTest {
}
```
### 의존성 주입
```java
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@TestPropertySource(locations = "classpath:test.properties")
@Import(ValidationAndExceptionTestConfig.class)
public class ValidationAndExceptionTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private PromptTemplateRequest idNull;
@Autowired
private PromptTemplateRequest contentNull;
@Autowired
private PromptTemplateRequest templateRequest;
@Autowired
private PromptTemplateService service;
@Autowired
private Map<String, String> map;
}
```
### 메서드 작성
#### 주입 여부 확인
```java
@Test
public void testExistence(){
assertNotNull(mockMvc);
assertNotNull(idNull);
assertNotNull(contentNull);
assertNotNull(templateRequest);
assertNotNull(service);
assertNotNull(map);
}
```
#### 검증 테스트(`BadRequestException`)
```java
@Test
public void testBadRequestExceptionIdNull() throws Exception {
mockMvc.perform(post("/prompt-template")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(idNull)))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8"))
.andDo(MockMvcResultHandlers.print(System.out));
}
@Test
public void testBadRequestExceptionContentNull() throws Exception {
mockMvc.perform(post("/prompt-template")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(contentNull)))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8"))
.andDo(MockMvcResultHandlers.print(System.out));
}
```
#### 예외 처리 테스트
```java
@Test
public void testEntityNotFoundException() throws Exception {
mockMvc.perform(get("/prompt-template/%s".formatted(contentNull.getId())))
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8"))
.andDo(MockMvcResultHandlers.print(System.out));
}
@Test
public void testInternalServerError() throws Exception {
service.create(templateRequest.toEntity());
mockMvc.perform(
post("/prompt/generated-by/prompt-template/%s".formatted(templateRequest.getId()))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(map)))
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE + ";charset=UTF-8"))
.andDo(MockMvcResultHandlers.print(System.out));
}
```
## [[9. JSR-303과 Spring Validator를 통한 데이터 검증|검증 코드 작성]] & [[10. @ControllerAdvice를 통한 예외 처리|예외처리 코드 작성]]
## 테스트 결과 확인
![[Pasted image 20231215154245.png]]