TEST CLASS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package me.hip.test;
@Test
@TestDescription("정상적으로 이벤트를 생성하는 테스트")
public void createEvent() throws Exception{
EventDTO event=EventDTO.builder()
.name("Spring")
.description("REST API Develompomer")
.beginEnrollmentDateTime(LocalDateTime.now())
.closeEnrollmentDateTime(LocalDateTime.of(2019,11, 11, 11, 50))
.beginEventDateTime(LocalDateTime.now())
.endEventDateTime(LocalDateTime.of(2019,11,26,10,50))
.basePrice(100)
.maxPrice(200)
.limitOfEnollment(100)
.location("강남역 D2 스타텁 팩토리")
.build();
mockMvc.perform(post("/api/events/")
.contentType(MediaType.APPLICATION_JSON_UTF8) //서버로 보내는 데이터(body)의 타입을 정의함 메시지 내용이 json 이며 문자열은 utf-8 문자열설정
.accept(MediaTypes.HAL_JSON) //서버에 이러한 타입의 데이터를 보내줫으면 좋겟다고 명시할때 사용함 HAL+json
.content(objectMapper.writeValueAsString(event))) //서버에 보내는 데이터를 정의함 objectMapper 해당 메서드로 event객체 내에있는 데이터를 json으로 변환
.andDo(print()) //처리 내용을 출력함
.andExpect(status().isCreated()) //상태값은 201(api docs에 정의)이 나와야함
.andExpect(jsonPath("id").exists()) //response json id 가 비어있지 않아야한다.
.andExpect(header().exists(HttpHeaders.LOCATION)) //header 에 location 항목이 비어있지 않아야한다.
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaTypes.HAL_JSON_UTF8_VALUE)) //header에 content-type 항목에 타입이 hal+json 문자열 utf-8 이여야함
.andExpect(jsonPath("id").value(Matchers.not(100))) //id 로 받은 json 의 값이 100이면 안된다.
.andExpect(jsonPath("free").value(Matchers.not(true))) //free로 받은 json 의 값이 true면 안된다.
.andExpect(jsonPath("eventStatus").value(EventStatus.DRAFT.name())); //{"eventStatus":"DRAFT"} 이라는 response를 받았는지 검증하려면 아래처럼 사용하세요.
System.out.println(objectMapper.writeValueAsString(event));
System.out.println("테스트 종료");
}
|
cs |
CONTROLLER
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
package com.example.demo.event;
import java.net.URI;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.MediaType;
//import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping(value="/api/events",produces=MediaTypes.HAL_JSON_UTF8_VALUE,consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
//produces = 설정과 Accept request 헤더가 일치할 경우에만 호출됨
//consumes = 설정과 Content request 헤더가 일치할 경우에만 호출됨
@Controller
public class EventController {
@Autowired
private EventRepository eventRepository;
@Autowired
private ModelMapper modelMapper;
@Autowired
private EventValidator eventValidator;
@PostMapping
public ResponseEntity createEvent(@RequestBody @Valid EventDTO eventDTO,Errors errors,HttpServletResponse response) {
System.out.println(errors.hasErrors());
if(errors.hasErrors()) { //객체 검증 엇나가면 true
System.out.println(errors.hasErrors());
return ResponseEntity.badRequest().build();
}
eventValidator.validate(eventDTO, errors); //객체 예외사항 다시 검증
if(errors.hasErrors()) {
System.out.println(errors);
return ResponseEntity.badRequest().build();
}
Event event=modelMapper.map(eventDTO, Event.class); //modelMapper 라이브러리 사용하여 eventDTO로받은 데이터를 Event로 매핑함
System.out.println(event);
Event event1=eventRepository.save(event);
System.out.println("save 후="+event1);
URI uri=
ControllerLinkBuilder.linkTo(EventController.class).slash(99).toUri();
//slash 메서드는 도메인/slash매개변수 linkTo는 잘모르겠다
Cookie cookie=new Cookie("das", "test");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
return ResponseEntity.created(uri).body(event1); //body에 객체를 담아 json 리턴
}
}
|
cs |
EventValidator
컨트롤러에서 객체 예외사항을 다시 검증할때 사용함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.example.demo.event;
import java.time.LocalDateTime;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
@Component
public class EventValidator {
public void validate(EventDTO eventDTO,Errors errors) {
if(eventDTO.getBasePrice()>eventDTO.getMaxPrice()&& eventDTO.getMaxPrice()!=0) {
errors.rejectValue("basePrice", "wrongValue","BasePrice is Wrong");
errors.rejectValue("maxPrice", "wrongValue","MaxPrice is Wrong");
}
LocalDateTime endEventDateTime=eventDTO.getEndEventDateTime();
if(endEventDateTime.isBefore(eventDTO.getBeginEventDateTime())||endEventDateTime.isBefore(eventDTO.getCloseEnrollmentDateTime())||
endEventDateTime.isBefore(eventDTO.getBeginEnrollmentDateTime())) {
errors.rejectValue("endEventDateTime", "wrongValue","endEventDateTime is Wrong");
}
//TODO BeginEventDateTime
//TODO CloseEnrollmentDateTime
}
}
|
cs |
'JAVA > SPRING' 카테고리의 다른 글
Dispatcher Servlet 작동방식 (0) | 2020.10.18 |
---|