spring

Junit 개념 및 활용

개발만파볼까 2021. 7. 24. 13:55
728x90
반응형
SMALL

회사에서 설계/개발을 하고 테스트를 기존에 만들어진 웹 페이지로만 진행했기 떄문에, 군데군데 숨어있는 버그를 찾지 못하고 짜짤짜잘한 이슈들이 나오는 경우가 있었다. 최근에 유튜브에서 더 나은 개발자로 성장하기 위해서는 테스트코드를 잘 작성하라는 말이 나오면서 이번에 springboot에 존재하는 junit에 대해 다뤄볼까 한다. 

 

Junit이란? 

- Java에서 단위테스트를 지원해주는 프레임워크

 

 

Junit 문법

  • @BeforeClass : 테스트 시작시 1번만 호출 
  • @Before : 테스트 시작전 호출
  • @After : 테스트 완료시 호출
  • @AfterClass : 모든 테스트 완료시 1번 호출

 

Junit 간단소스

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class Test2 {
	
   private static final Logger logger = LoggerFactory.getLogger(Test2.class);
	
    @Before
    public void before() {
    	logger.info("@Before");
    }

    @After
    public void after() {
    	logger.info("@After");
    }

    @Test
    public void testCase1() {
    	logger.info("@testCase1");
    }

    @Test
    public void testCase2() {
    	logger.info("@testCase2");
    }
}

 

Junit 간단소스 테스트 결과

...

2021-07-23 14:08:23.836  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @Before
2021-07-23 14:08:23.837  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @testCase1
2021-07-23 14:08:23.840  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @After
2021-07-23 14:08:23.855  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @Before
2021-07-23 14:08:23.856  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @testCase2
2021-07-23 14:08:23.857  INFO 11888 --- [           main] c.sideproject.bankcheck.junittest.Test2  : @After

...

 

이렇게 간단하게 테스트 코드를 구현/실행으로만 끝난다면 테스트 코드를 짜야하는 명분을 찾을 수 없어서, 상황을 주고, 그 상황에 따라 테스트 코드를 한 번 개선시켜보겠다. 

 

상황 : 게시판을 글 쓰고 최근글이 가장 상단에 있는지 테스트를 할려고 함

확인이 되면, 게시판 글에 대해 쓰기/조회가 잘 나오는걸로 확인할 수 있음

 

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class Class1Tests {
	
	private static final Logger logger = LoggerFactory.getLogger(Class1Tests.class);
	
	@Autowired
	private BoardService boardService;
	
	private long boardNo;
	
	
	@Before
	@DisplayName("게시판 저장하기")
	public void setup() {
		logger.info("setup");
		BoardDto boardDto = new BoardDto();
		boardDto.setTitle("테스트"); 
		boardDto.setAuthor("테스터");
		boardDto.setContent("졸려죽겠다..ㅜㅜㅜㅜㅜㅜ"); 
		boardNo = boardService.savePost(boardDto);
		logger.info("result = " + boardNo);
		assertTrue(boardNo != 0);
	}
	

	
	@Test
	@DisplayName("게시판 불러오기")
	public void list() {
		logger.info("list");
		List<BoardDto> boardList = boardService.getBoardList();
		assertTrue(boardList.get(0).getId() == boardNo);
	}
}

로직은 게시판글을 쓰고나면 idx값이 리턴이 되고, 게시판을 조회하면 가장 최근에 쓴 글부터 차례로 조회가 되어지는데, assertTrue를 통해서 가장 최근에 쓴 글이 보여지는지를 확인할 수 있겠끔 했다. 

 

결과는? 

 

...

2021-07-24 13:43:23.197  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 테스트 속도 시작
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2021-07-24 13:43:23.390  INFO 5920 --- [           main] com.sun.proxy.$Proxy114                  : response: com.sideproject.bankcheck.domain.entity.BoardEntity@5db6083b
2021-07-24 13:43:23.390  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 테스트 속도 끝
2021-07-24 13:43:23.391  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 걸린시간: 192 ms
2021-07-24 13:43:23.391  INFO 5920 --- [           main] c.s.bankcheck.service.BoardService       : response: 15
Hibernate: insert into board_entity (author, content, created_date, modified_date, title, id) values (?, ?, ?, ?, ?, ?)
2021-07-24 13:43:23.485  INFO 5920 --- [           main] c.s.bankcheck.junittest.Class1Tests      : result = 15
2021-07-24 13:43:23.490  INFO 5920 --- [           main] c.s.bankcheck.junittest.Class1Tests      : list
2021-07-24 13:43:23.494  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 테스트 속도 시작
Hibernate: select boardentit0_.id as id1_0_, boardentit0_.author as author2_0_, boardentit0_.content as content3_0_, boardentit0_.created_date as created_4_0_, boardentit0_.modified_date as modified5_0_, boardentit0_.title as title6_0_ from board_entity boardentit0_ order by boardentit0_.id desc
2021-07-24 13:43:23.694  INFO 5920 --- [           main] com.sun.proxy.$Proxy114                  : response: [com.sideproject.bankcheck.domain.entity.BoardEntity@1131fcfd, com.sideproject.bankcheck.domain.entity.BoardEntity@13c36d48, com.sideproject.bankcheck.domain.entity.BoardEntity@7e93e396, com.sideproject.bankcheck.domain.entity.BoardEntity@f1e8753, com.sideproject.bankcheck.domain.entity.BoardEntity@1676e501, com.sideproject.bankcheck.domain.entity.BoardEntity@1ed763aa, com.sideproject.bankcheck.domain.entity.BoardEntity@7f39bcb5, com.sideproject.bankcheck.domain.entity.BoardEntity@4e6881e, com.sideproject.bankcheck.domain.entity.BoardEntity@25192b6e, com.sideproject.bankcheck.domain.entity.BoardEntity@76d654, com.sideproject.bankcheck.domain.entity.BoardEntity@32180efb, com.sideproject.bankcheck.domain.entity.BoardEntity@20ed6de]
2021-07-24 13:43:23.695  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 테스트 속도 끝
2021-07-24 13:43:23.695  INFO 5920 --- [           main] com.sideproject.bankcheck.aop.LogAspect  : 걸린시간: 200 ms
2021-07-24 13:43:23.695  INFO 5920 --- [           main] c.s.bankcheck.service.BoardService       : response: [BoardDto(id=15, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜㅜㅜㅜ, createdDate=2021-07-24T13:43:23.269157, modifiedDate=null), BoardDto(id=14, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜㅜㅜㅜ, createdDate=2021-07-24T13:42:27.261726, modifiedDate=null), BoardDto(id=13, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜㅜㅜㅜ, createdDate=2021-07-24T13:38:36.399150, modifiedDate=null), BoardDto(id=12, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜㅜㅜㅜ, createdDate=2021-07-24T01:57:03.407207, modifiedDate=null), BoardDto(id=11, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜㅜ, createdDate=2021-07-23T16:51:44.610559, modifiedDate=null), BoardDto(id=10, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜㅜ, createdDate=2021-07-23T16:50:30.151871, modifiedDate=null), BoardDto(id=9, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜ, createdDate=2021-07-22T01:17:45.809399, modifiedDate=null), BoardDto(id=8, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜ, createdDate=2021-07-22T00:54:37.225638, modifiedDate=null), BoardDto(id=7, author=테스터, title=테스트, content=졸려죽겠다..ㅜㅜ, createdDate=2021-07-22T00:53:21.833892, modifiedDate=null), BoardDto(id=6, author=최성진, title=오늘은 제헌절, content=그렇죠?, createdDate=2021-07-17T13:34:53.041212, modifiedDate=null), BoardDto(id=5, author=성진, title=오늘은 몇일일까요?, content=ㅌㅌㅌㅌㅌㅌ, createdDate=2021-04-18T19:45:51.132827, modifiedDate=null), BoardDto(id=4, author=작성자인가?, title=제목인가?, content=내용인가? , createdDate=2021-04-18T04:08:58.343437, modifiedDate=null)]
2021-07-24 13:43:23.725  INFO 5920 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2021-07-24 13:43:23.735  INFO 5920 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-07-24 13:43:23.739  INFO 5920 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-07-24 13:43:23.781  INFO 5920 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

...

성공을 하게 되면 초록색으로 뜨게 되고 테스트를 실패하게 되면 빨간색으로 표시된다.

 

해당 부분은 로컬로 테스트해서 junit을 하는데 이상이 없었지만, 외부 api response을 통해 로직이 움직이는 케이스에 대해서는 해당 문법만 가지고는 테스트하기가 어렵다. 이 상황에 대해서는 mockito를 써야한다는 것을 알게 되었다. 

그래서 다음 시간에는 Junit에서의 mockito에 대해 설명할까 한다. 

728x90
반응형
LIST