Mockito : Mock 객체 확인 및 BDD 스타일 Mockito API

YoungG209·2022년 1월 4일
0

인프런의 "더 자바, 애플리케이션을 테스트하는 다양한 방법”을 보고 정리한 것임

1. Mock 객체 확인

// 1,2 만 확인함
    @Test
    void createNewStudy() {
        StudyService studyService = new StudyService(memberService, studyRepository);
        assertNotNull(studyService);

        Member member = new Member();
        member.setId(1L);
        member.setEmail("lee@gamil.com");

        Study study = new Study(10, "테스트");

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

        studyService.createNewStudy(1L, study);

        assertNotNull(study.getOwner());
        assertEquals(member, study.getOwner());

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

        verifyNoMoreInteractions(memberService);
//
//        verify(memberService, times(1)).notify(member);
//        verify(memberService, never()).validate(any());
//
//        InOrder inOrder = inOrder(memberService);
//        inOrder.verify(memberService).notify(study);
//
//        inOrder.verify(memberService).notify(member);
    }

2. BDD 스타일 Mockito API

BDD란?

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

행동에 대한 스팩

  • Title
  • Narrative
    • As a / I want / so that
  • Acceptance criteria
    • Given / When / Then

Mockito BDD 스타일의 API

  • BddMockito라는 클래스 존재
    @Test
    void bddStyle() {
        // Given
        StudyService studyService = new StudyService(memberService, studyRepository);
        assertNotNull(studyService);

        Member member = new Member();
        member.setId(1L);
        member.setEmail("lee@gamil.com");

        Study study = new Study(10, "테스트");

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

        // When
        studyService.createNewStudy(1L, study);

        // Then
        assertEquals(member, study.getOwner());

//        verify(memberService, times(1)).notify(study);
        then(memberService).should(times(1)).notify(study);

//        verifyNoMoreInteractions(memberService);
        then(memberService).shouldHaveNoMoreInteractions();
    }
profile
고우고우~

0개의 댓글