본문 바로가기
Spring/boot

spring-boot Controller Mock Testcase 작성

by 무대포 개발자 2020. 9. 5.
728x90
반응형

spring boot controller test (mock 버전)

  • java source

import org.example.online.domain.SampleIO;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {
    @RequestMapping(value ="test/{id}", method = RequestMethod.GET)
    public SampleIO getTestData(@PathVariable("id") Long id) {
        SampleIO testIO = SampleIO.builder()
                .id(id)
                .name("test")
                .build();
        return testIO;
    }
}



import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class SampleIO {
    private long id;
    private String name;

    @Builder
    public SampleIO(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public SampleIO(String name) {
        this.name = name;
    }
}



@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleControllerTest {

    private MockMvc mockMvc;

    @MockBean
    private SampleController sampleController;

    private SampleIO sampleIO;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(sampleController).build();
        sampleIO = SampleIO.builder()
                .id(100)
                .name("Test")
                .build();
    }

    @Test
    public void sampleControllerTest() throws Exception {

        /** 100 이라는 값이 들어왔을 때, 아래 값을 주도록 하기. */
        given(this.sampleController.getTestData(new Long(100)))
                .willReturn(sampleIO);

        mockMvc.perform(get("/test/{id}", 100))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$['name']", containsString("Test")))
                .andDo(print());
    }
}



build.gradle

compile('org.springframework.boot:spring-boot-starter-web')
testImplementation('org.springframework.boot:spring-boot-starter-test')

장애

  • IllegalARgumentException PathVariable name 을 못찾는다는 거였는데.
  • 해결방안은 다음 링크 참고

댓글