스프링부트와 AWS로 혼자 구현하는 웹서비스

04. Hello Controller 테스트 코드 작성하기

Mary's log 2024. 10. 19. 22:51

[개발 환경]  mac M3 Sonoma 14 /  java 11 /  gradle 7.0 /  intellij Community 2024.2.4

 

 

 

src\main\java - 새로 만들기 - 패키지

 

 

com.jojoldu.book.springboot

 

springboot 하위에 Java 클래스 Application 생성

 

 

src.main.java.com.jojoldu.book.springboot\Application.java

 

import 먼저 적고,

어노테이션 적고,

class 안에서는 'main' 글자만 입력하면 자동완성 함수가 나온다.

run 함수를 적는다.

package com.jojoldu.book;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

사용할 함수만 미리 적고 자동 import할 수도 있다.

 

* Import 자동완성 목록 단축키

Win, Linux : Alt + Enter

mac : Option + Enter

 


src.main.java.com.jojoldu.book.springboot.web 생성

src.main.java.com.jojoldu.book.springboot.web\HelloController.java 생성

package com.jojoldu.springboot.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

 

 


 

 

* 오류 해결

 

src.main.java.com.jojoldu.springboot.web 를 만든 것처럼

src.test.java.com.jojoldu.springboot.web 경로를 만든다.

 

HelloControllerTest.java 생성.

package com.jojoldu.springboot.web;

import com.jojoldu.springboot.web.HelloController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void helloReturn() throws Exception {
        String hello = "hello";
        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }
}

 

 

@Test 어노테이션이 있는 함수helloReturn 왼쪽 줄라인에 보이는 ▷을 눌러야함.

 

 

 

test에서는 성공했다.

실제 main함수가 있는 Application.java에서도 정상 동작하는지 확인.

 

 

* Win에서 할 땐 포트 8080로는 오류났었는데(이미 사용중 포트였어서 다른 포트로 설정 잡아줬었다, 검색하면 해결법 잘 나올 것이다..)

   mac에서 하니까 오류가 안난다. 이유는 모르겠다...

 

크롬 브라우저 주소창에 localhost:8080/hello 요청 

 

잘 나온다.