๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Spring

์Šคํ”„๋ง ๋ถ€ํŠธ ํ…Œ์ŠคํŠธ - ๋‚ด์žฅ ์„œ๋ฒ„ ๋žœ๋ค ํฌํŠธ๋กœ ๋„์šฐ๊ธฐ

by Leica 2020. 3. 24.
๋ฐ˜์‘ํ˜•

์Šคํ”„๋ง ๋ถ€ํŠธ ํ…Œ์ŠคํŠธ - ๋‚ด์žฅ ์„œ๋ฒ„ ๋žœ๋ค ํฌํŠธ๋กœ ๋„์šฐ๊ธฐ

 

๐Ÿ‘‰ Dependency

spring-boot 2.2.5.RELEASE
junit 4.12

 

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebtoonApiControllerTest {

    @LocalServerPort
    private int port;

    @Test
    public void printPort() throws Exception {
        System.out.println(port);
        assertNotEquals(port, 0);
    }
    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @Test
    // Do some test...
}

 

๐Ÿ“‘ WebEnvironment.RANDOM_PORT

@SpringBootTest์˜ webEnvironment ์†์„ฑ์€ ํ…Œ์ŠคํŠธ์˜ ์›น ํ™˜๊ฒฝ์„ ์„ค์ •ํ•˜๋Š” ์†์„ฑ์ด๋ฉฐ ๊ธฐ๋ณธ๊ฐ’์€ SpringBootTest.WebEnvironment.MOCK์ด๋‹ค.

WebEnvironment.MOCK์€ ์‹ค์ œ ์„œ๋ธ”๋ฆฟ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ๋„์šฐ์ง€ ์•Š๊ณ  ์„œ๋ธ”๋ฆฟ ์ปจํ…Œ์ด๋„ˆ๋ฅผ mockingํ•œ๊ฒƒ์ด ์‹คํ–‰๋œ๋‹ค.

์ด ์†์„ฑ๊ฐ’์„ ์‚ฌ์šฉํ• ๋•Œ๋Š” ๋ณดํ†ต MockMvc๋ฅผ ์ฃผ์ž…๋ฐ›์•„ ํ…Œ์ŠคํŠธํ•œ๋‹ค.

 

๋‹ค์‹œ ํฌ์ŠคํŒ…์˜ ์ฃผ์ œ๋กœ ๋Œ์•„๊ฐ€์„œ ์Šคํ”„๋ง ๋ถ€ํŠธ์˜ ๋‚ด์žฅ ์„œ๋ฒ„๋ฅผ ๋žœ๋ค ํฌํŠธ๋กœ ๋„์šฐ๋ ค๋ฉด webEnvironment๋ฅผ SpringBootTest.WebEnvironment.RANDOM_PORT๋กœ ์„ค์ •ํ•˜๋ฉด ๋œ๋‹ค.

์ด ์„ค์ •์€ ์‹ค์ œ๋กœ ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•œ ์„œ๋ธ”๋ฆฟ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ๋„์šด๋‹ค.

WebEnvironment.MOCK์„ ์‚ฌ์šฉํ• ๋•Œ์™€๋Š” ๋‹ฌ๋ฆฌ TestRestTemplate๋ฅผ ์ฃผ์ž…๋ฐ›์•„ ํ…Œ์ŠคํŠธํ•œ๋‹ค.

 

printPort() ์‹คํ–‰ ๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€