본문 바로가기

Java/Test

(Test) BDD 스타일 Mockito API

BDD: 애플리케이션이 어떻게 “행동”해야 하는지에 대한 공통된 이해를 구성하는 방법으로, TDD에서 창안했다.

 

행동에 대한 스펙

  • Title

  • Narrative

    • As a  / I want / so that

  • Acceptance criteria

    • Given / When / Then

 

Mockito는 BddMockito라는 클래스를 통해 BDD 스타일의 API를 제공한다.

 

When -> Given

given(memberService.findById(1L)).willReturn(Optional.of(member));

given(studyRepository.save(study)).willReturn(study);

 

Verify -> Then

then(memberService).should(times(1)).notify(study);

then(memberService).shouldHaveNoMoreInteractions();

 

Mockito - mockito-core 3.2.4 javadoc

Latest version of org.mockito:mockito-core https://javadoc.io/doc/org.mockito/mockito-core Current version 3.2.4 https://javadoc.io/doc/org.mockito/mockito-core/3.2.4 package-list path (used for javadoc generation -link option) https://javadoc.io/doc/org.m

javadoc.io

 

BDDMockito (Mockito 3.2.0 API)

Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. This is exactly how we write our tests and we warmly encourage you to do so! Start learning about BDD here: http://en.wikipedi

javadoc.io


when(memberService.findById(1L)).thenReturn(Optional.of(member));
when(studyRepository.save(study)).thenReturn(study);

위의 코드는 BDD에서 Given에 해당하는 부분이지만 when이 선언돼있다. (문맥상으로는 옳지만 코드상으로 의미가 안 맞는 느낌)

 

 

when을 given으로 변경

given(memberService.findById(1L)).willReturn(Optional.of(member));
given(studyRepository.save(study)).willReturn(study);

 

Verify를 then으로 변경

변경 이전

verify(memberService, times(1)).notify(study);

변경 이후

then(memberService).should(times(1)).notify(study);

 

shouldHaveNoMoreInteractions

변경 이전

verifyNoMoreInteractions(memberService);

변경 이후

then(memberService).shouldHaveNoMoreInteractions();

원칙에 얽매이지 말고 그때그때 실용적인 측면에서 가장 어울리는 것을 사용하자!

 

 

코드 참조

https://github.com/mike6321/PURE_JAVA/tree/master/HowToTest/inflearn-the-java-test

 

mike6321/PURE_JAVA

Contribute to mike6321/PURE_JAVA development by creating an account on GitHub.

github.com

 

 

 

'Java > Test' 카테고리의 다른 글

(Test) Mock 객체 확인  (0) 2020.01.05
(Test) Mock 객체 Stubbing  (0) 2020.01.05
(Test) Mock 객체 만들기  (0) 2020.01.05
(Test) Mockito 란?  (0) 2020.01.01
(Test) JUit5 - JUnit4 Migration  (0) 2020.01.01