본문 바로가기
프로그래밍/Java & Spring

Spring4 Junit 테스트 코드 작성기

by 방구석개발자 2021. 9. 20.
반응형

안녕하세요. 방구석 개발자입니다.

현재 프로젝트는 스프링4, 전자정부프레임워크를 이용하여 진행하고 있습니다.

스프링부트가 아니여서 아쉽지만 코드품질을 높이고자 테스트 코드를 작성하려고 합니다.

테스트 코드 작성

각 MVC 패턴에 맞게 테스트 코드가 이루어져야 된다고 생각하여 각 패턴에 맞는 샘플 테스트 코드를 작성해보겠습니다.

우선 pom.xml 에 필요한 dependecy 추가했습니다.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.22.RELEASE</version>
    <scope>test</scope>
</dependency>

ControllerTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:egovframework/spring/context/**/context-*.xml"})
@WebAppConfiguration
public class ManageControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup(){
        //this.mockMvc=MockMvcBuilders.webAppContextSetup(this.wac).build();
        this.mockMvc=MockMvcBuilders.standaloneSetup(new ManageController()).build();
    }

    @Test
    public void manageDetailTest() throws Exception {
        //assertThat("test").isEqualTo("test");
        mockMvc.perform(MockMvcRequestBuilders.get("/manage/detail"))
            .andExpect(view().name("sur/manage/survey-view.default"))
            .andExpect(status().isOk());
    }

}

ServiceTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:egovframework/spring/context/**/context-*.xml"})
@WebAppConfiguration
@Transactional
public class ManageServiceImplTest {

    @Autowired
    private ManageService manageService;
    private MngDTO vo;

    @Before
    public void setup(){
        vo=new MngDTO();
    }

    @Test
    public void getMnglistTest_목록검증() {
        List<MngDTO> list= (List<MngDTO>) manageService.getMnglist(vo);
        assertThat(list.stream().findFirst().get().getNm()).isEqualTo("테스트");
    }

    @Test
    public void getMnglistCntTest_개수검증(){
        int result=manageService.getMnglistCnt(vo);
        assertThat(9012).isEqualTo(result);
    }
}

앞으로는?

TDD를 하고 싶었지만 실제로 코드를 짜보니 쉽지 않았습니다.

그렇지만 계속해서 지향하여 TDD로 개발하는 방법을 익힐 것이고 테스트 코드 커버리지를 확인 하여 전체 코드 품질을 높이겠습니다.

감사합니다.

반응형

댓글