관리 메뉴

bright jazz music

blog01 : 프로젝트 생성/기본 RestController 생성/테스트 수행 본문

Projects/blog

blog01 : 프로젝트 생성/기본 RestController 생성/테스트 수행

bright jazz music 2022. 12. 10. 13:08

 

 

/*build.gradle*/

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.7.6'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

group = 'com.endofma'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

 

 

 

 

 

//PostController.java

package com.endofma.blog.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PostController {

    @GetMapping("/posts")
    public String get(){
        return "hello world";
        // ctrl + Shift + t = Test 파일 만들기
    }

}

 

 

//PostControllerTest.java

package com.endofma.blog.controller;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
class PostControllerTest {
    @Autowired
    private MockMvc mockMvc; ////Could not autowire. No beans of 'MockMvc' type found.

    @Test
    @DisplayName("/posts 요청시 hello world를 출력한다")
    void test() throws Exception {
        //expected
        mockMvc.perform(get("/posts"))
                .andExpect(status().isOk())			//http response 가 200인지
                .andExpect(content().string("hello world"))	// 내용이 hello world인지
                //.andExpect(content().string("Bye world")) 바디의 내용이 다르다.
                .andDo(print());				//요청에 대한 전반적인 요약을 출력해준다.

    }

}

 

Could not autowire. No beans of 'MockMvc' type found.

인텔리제이 2022.3 버전을 설치하여 해결. @SuppressWarning을 사용하여 컴파일 시 무시하게 만들라는 글도 있었지만 어차피 앞으로는 신규 버전을 사용해야하므로 업데이트 하였다.

 

인텔리제이 사이트에서 신규 버전 설치 클라이언트를 다운받아서 새로 설치했다는 뜻이다. 설치 클라이언트가 기존에 설치된 프로그램을 제거하고 설치할지 물어본다. 모두 동의하고 설치하면 된다.

 

 

 

PostControllerTest.test 실행

요청에 대해서 정상적으로 접근하였을 경우.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.6)

2022-12-12 09:11:52.546  INFO 5660 --- [    Test worker] c.e.blog.controller.PostControllerTest   : Starting PostControllerTest using Java 11.0.12 on DESKTOP-Q7HBM41 with PID 5660 (started by user in D:\personal\work\blog)
2022-12-12 09:11:52.548  INFO 5660 --- [    Test worker] c.e.blog.controller.PostControllerTest   : No active profile set, falling back to 1 default profile: "default"
2022-12-12 09:11:54.309  INFO 5660 --- [    Test worker] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2022-12-12 09:11:54.310  INFO 5660 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2022-12-12 09:11:54.311  INFO 5660 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 1 ms
2022-12-12 09:11:54.359  INFO 5660 --- [    Test worker] c.e.blog.controller.PostControllerTest   : Started PostControllerTest in 2.452 seconds (JVM running for 4.994)

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /posts
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.endofma.blog.controller.PostController
           Method = com.endofma.blog.controller.PostController#get()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"11"]
     Content type = text/plain;charset=UTF-8
             Body = hello world
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
BUILD SUCCESSFUL in 8s
4 actionable tasks: 2 executed, 2 up-to-date
AM 9:11:55: Execution finished ':test --tests "com.endofma.blog.controller.PostControllerTest.test"'.

 

Body의 내용이 다른 경우

.andExpect(content().string("Bye world"))

.andDo(print()); //오류가 발생한 경우에는 프린트를 작성하지 않아도 내용을 요약해 준다.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.6)

2022-12-12 09:20:42.351  INFO 9052 --- [    Test worker] c.e.blog.controller.PostControllerTest   : Starting PostControllerTest using Java 11.0.12 on DESKTOP-Q7HBM41 with PID 9052 (started by user in D:\personal\work\blog)
2022-12-12 09:20:42.353  INFO 9052 --- [    Test worker] c.e.blog.controller.PostControllerTest   : No active profile set, falling back to 1 default profile: "default"
2022-12-12 09:20:44.061  INFO 9052 --- [    Test worker] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2022-12-12 09:20:44.062  INFO 9052 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2022-12-12 09:20:44.063  INFO 9052 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 1 ms
2022-12-12 09:20:44.106  INFO 9052 --- [    Test worker] c.e.blog.controller.PostControllerTest   : Started PostControllerTest in 2.328 seconds (JVM running for 4.914)

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /posts
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.endofma.blog.controller.PostController
           Method = com.endofma.blog.controller.PostController#get()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"11"]
     Content type = text/plain;charset=UTF-8
             Body = hello world
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Response content expected:<bye world> but was:<hello world>
Expected :bye world
Actual   :hello world
<Click to see difference>

java.lang.AssertionError: Response content expected:<bye world> but was:<hello world>
	at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
	at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
	at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$string$4(ContentResultMatchers.java:148)
	
    ... 생략...
	
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
	at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)


PostControllerTest > /posts 요청시 hello world를 출력한다 FAILED
    java.lang.AssertionError at PostControllerTest.java:31
1 test completed, 1 failed
> Task :test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> There were failing tests. See the report at: file:///D:/personal/work/blog/build/reports/tests/test/index.html
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 8s
4 actionable tasks: 2 executed, 2 up-to-date

 

 

 

Comments