JUnit4 테스트 코드 작성해보기, @Before

Kim Dong Kyun·2023년 4월 11일

Junit 이용한 테스트 코드 작성

1. 테스트 코드의 작성 기준

  1. 코드가 정상적으로 동작하는지 확신하려고 추가적인 테스트를 작성할 필요가 있는가?
  2. 내가 클래스에서 결함이나 한계점을 드러낼 수 있는 테스트를 작성했는가?

2. Junit에서 테스트는 고유 맥락을 갖는다.

  • 결정된 순서로 테스트를 실행하지 않는다.
  • 모든 테스트는 다른 테스트 결과에 영향을 받지 않는다.
  • 따라서, 인스턴스 생성 등 중복되는 로직이 필연적으로 발생하며, 이는 @Before 어노테이션으로 모듈화 가능하다.

예시

	@Test
	public void matchesAnswerFalseWhenMustMatchCriteriaNotMet(){
		Profile profile1 = new Profile("B B");
		Question question1 = new BooleanQuestion(1, "Got bonuses?");
		Criteria criteria1 = new Criteria();
		Answer criteriaAnswer = new Answer(question1, Bool.TRUE);
		Criterion criterion = new Criterion(criteriaAnswer, Weight.MustMatch);
		criteria.add(criterion);

		boolean matches = profile1.matches(criteria1);

		assertFalse(matches);
	}

	@Test
	public void matchesAnswerTrueForAnyDontCareCriteria() {

		Profile profile1 = new Profile("B B");
		Question question1 = new BooleanQuestion(1, "Got Milk?");
		Answer profileAnswer = new Answer(question1, Bool.FALSE);
		profile1.add(profileAnswer);
		Criteria criteria1 = new Criteria();
		Answer criteriaAnswer = new Answer(question1, Bool.TRUE);
		Criterion criterion = new Criterion(criteriaAnswer, Weight.DontCare);
		criteria1.add(criterion);

		boolean matches = profile1.matches(criteria1);

		assertTrue(matches);
	}

위 코드는 모두 프로필, 퀘스천, 앤서 객체를 중복되게 생성한다. 이런 식의 비효율을 다음과 같이 줄일 수 있다.


	@Before
	public void create() {
		profile = new Profile("Bull Hockey");
		question = new BooleanQuestion(1, "Got bonuses?");
		criteria = new Criteria();
	}

위와 같이 @Before 어노테이션 사용으로 인스턴스의 생성을 관리한다.


0개의 댓글