수색…


BDDMockito 스타일

Behavior Driven Development (BDD) 테스트 스타일은 테스트에서 "주어진", "언제"및 "그 다음"단계를 중심으로 이루어집니다. 그러나 고전적인 Mockito는 "주어진"단계의 "때"단어를 사용하고 BDD를 포함 할 수있는 다른 자연 언어 구조는 포함하지 않습니다. 따라서 행동 주도 테스트를 용이하게하기 위해 BDDMockito 별칭이 버전 1.8.0에 도입되었습니다.

가장 일반적인 상황은 메서드 반환을 스텁하는 것입니다. 다음 예에서 getStudent(String) 조롱의 방법 StudentRepository 돌아갑니다 new Student(givenName, givenScore) 와 동일한 인수로 호출하면 givenName .

import static org.mockito.BDDMockito.*;

public class ScoreServiceTest {

    private StudentRepository studentRepository = mock(StudentRepository.class);

    private ScoreService objectUnderTest = new ScoreService(studentRepository);

    @Test
    public void shouldCalculateAndReturnScore() throws Exception {
        //given
        String givenName = "Johnny";
        int givenScore = 10;
        given(studentRepository.getStudent(givenName))
            .willReturn(new Student(givenName, givenScore));

        //when
        String actualScore = objectUnderTest.calculateStudentScore(givenName);

        //then
        assertEquals(givenScore, actualScore);
    }
}

경우에 따라 종속성에서 발생 된 예외가 올바르게 처리되는지 또는 테스트중인 메소드에서 다시 throw되는지 여부를 확인하는 것이 좋습니다. 이러한 동작은 다음과 같이 "주어진"단계에서 스터브 될 수 있습니다.

willThrow(new RuntimeException())).given(mock).getData();

때로는 스텁 메소드가 소개해야하는 몇 가지 부작용을 설정하는 것이 바람직합니다. 특히 다음과 같은 경우에 유용 할 수 있습니다.

  • stubbed 메서드는 전달 된 개체의 내부 상태를 변경해야하는 메서드입니다.

  • 스터브 된 메서드는 void 메서드입니다.

이러한 행동은 "주어진"단계에서 "대답"으로 표시 할 수 있습니다.

willAnswer(invocation -> this.prepareData(invocation.getArguments()[0])).given(mock).processData();

모의 행위와의 상호 작용을 검증하고자 할 때 should() 또는 should(VerificationMode) (1.10.5부터) 메소드를 사용하여 "then"단계에서 수행 할 수 있습니다.

then(mock).should().getData(); // verifies that getData() was called once
then(mock).should(times(2)).processData(); // verifies that processData() was called twice

이미 확인 된 것 외에 모의 shouldHaveNoMoreInteractions() 와 더 이상 상호 작용이 없다는 것을 확인하고자 할 때 shouldHaveNoMoreInteractions() (2.0.0부터 shouldHaveNoMoreInteractions() 하여 "then"단계에서 수행 할 수 있습니다.

then(mock).shouldHaveNoMoreInteractions(); // analogue of verifyNoMoreInteractions(mock) in classical Mockito

모의 shouldHaveNoMoreInteractions() 와의 상호 작용이 전혀 없다는 것을 검증하고자 할 때 shouldHaveNoMoreInteractions() (2.0.0부터 shouldHaveNoMoreInteractions() 하여 "then"단계에서 수행 할 수 있습니다.

then(mock).shouldHaveZeroInteractions(); // analogue of verifyZeroInteractions(mock) in classical Mockito

메소드가 호출 된 순서 를 검사하기를 원할 때 should(InOrder) (1.10.5부터)와 should(InOrder, VerificationMode) (2.0.0부터)와 함께 "then"단계에서 수행 할 수 있습니다.

InOrder inOrder = inOrder(mock);

// test body here

then(mock).should(inOrder).getData(); // the first invocation on the mock should be getData() invocation
then(mock).should(inOrder, times(2)).processData(); // the second and third invocations on the mock should be processData() invocations


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow