22-07-12 ERROR [테스트 코드에 값이 안넘어온다.]

김설영·2022년 7월 12일

MyErrorLog

목록 보기
5/6

controller

DI : 
private final ArticleService articleService;

@GetMapping("/article/{id}")
public Article readArticle(@PathVariable Long id) {
    return articleService.findById(id).orElse(null);
}

TestCode

@DisplayName("/article/1 에 get 요청 시 id로 글이 조회된다.")
@Test
void readArticle() throws Exception {
    ArticleDto article = new ArticleDto();
    article.setText("본문입니다");
    article.setTitle("제목입니다");

    articleService.saveArticle(article);

    String json = "{\"title\": \"제목입니다\", \"text\" : \"본문입니다\", \"aid\" : 1 }";

    mockMvc.perform(MockMvcRequestBuilders.get("/article/1")
                    .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(json))
            .andDo(print());
}

결과



분명 PostMan으로 할 땐 잘 되는데, 왜 객체가 안넘어가는걸까?

일단 리포지토리 연결고리 역할을 하던 ArticleService 객체가 ArticleRepository와의 연관관계 주입으로 연결되어있다.

이게 역할을 못하는게 아닌가 했다. 그래서 급한대로 Article 엔티티에 세터를 추가하고 테스트 해봤는데, 역시나 값이 넘어오지 않았다.

일단, 테스트환경이기 때문에 리포지토리가 연결되지 않은 것으로 보인다. (스프링부트 테스트가 아니니깐..)

그럼 MockBean 으로 가짜 빈 객체를 만들어주면 해결이될까? 싶었다.

안된다.

구글링ㄱㄱ

나를 살려주신 분 : SpringBoot 1.4.0 Test 적용하기 (2)

최고의 글을 찾았다.

ArticleService를 WebMvcTest 환경에 어떻게 적용할까 하다가 import static org.mockito.BDDMockito.*given*; 패키지로 해결볼 수 있었다.

@DisplayName("/article/1 에 get 요청 시 id로 글이 조회된다.")
@Test
void readArticle() throws Exception {

    Article article = Article.builder()
            .text("text")
            .title("title")
            .build();

    // service 구현체가 없어도 테스트 가능!
    given(this.articleService.findById(1L))  // findById 메소드에 parameter=1이 입력될 경우
            .willReturn(article);  // article 객체를 리턴한다.

    String json = "{\"title\":\"title\",\"text\":\"text\",\"aid\":null}";

    mockMvc.perform(MockMvcRequestBuilders.get("/article/1")
                    .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(json))
            .andDo(print());
}

그리고 여담이지만 ```java (코드)```라고 적으니까 코드가 이뻐지는거 이제알았다.

profile
블로그 이동하였습니당! -> https://kimsy8979.tistory.com/

0개의 댓글