2017-11-06 4 views
0
when(mockObj.method(param1, param2)).thenReturn(1); 
when(mockObj.method(param1, param2)).thenReturn(2); 

조롱 된 개체에서 동일한 인수 목록을 가진 메서드의 값을 반환하는 충돌하는 문이있는 경우 최근 when/thenReturn이 반환되었습니다. 따라서 아래 진술이 사실 일 것입니다.Mockito : when(). thenThrow() 함수의 작동 방식 이해

assertEquals(2, mockObj.method(param1, param2)); 

예외를 throw하는 충돌하는 문이있는 경우 동작은 위와 같지 않습니다. 예를 들어 ,

@Test(expected = ExceptionTwo.class) 
public void testMethod() { 
    when(mockObj.method(param1, param2)).thenThrow(ExceptionOne.class); 
    when(mockObj.method(param1, param2)).thenThrow(ExceptionTwo.class); 
    mockObj.method(param1, param2); 
} 

이 테스트 케이스에 실패했습니다. 어떤 설명이 도움이 될 것입니다.

+0

https://stackoverflow.com/questions/31512245/calling-mockito-when-multiple-times-on-same-object 아래 답변과 함께 더 많은 통찰력을 제공하는 것 같습니다 !! –

답변

2

로 병합 할 수 있습니다 :

Warning : if instead of chaining .thenReturn() calls, 
multiple stubbing with the same matchers or arguments is used, 
then each stubbing will override the previous one. 

그래서 두 번째는 첫 번째보다 우선합니다. 따라서, 다른 경우 2. , 당신은 here을 참조 할 수 있습니다 반환 :
when(mock.foo()).thenThrow(new RuntimeException()); 

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. 
when(mock.foo()).thenReturn("bar"); 

//You have to use doReturn() for stubbing: 
doReturn("bar").when(mock).foo(); 

당신이 when..thenReturn를 사용

에서, 스텁 메소드가 호출됩니다. 조롱 된 객체에서 호출되었으므로 처음에는 관찰하지 않았습니다. 그러나 두 번째로 when을 작성하면 mock.foo()에 대한 일부 동작이 발생합니다 (이전에 Exception을 발생 시키도록 설정 한 경우). 따라서 두 번째 when (..) 문은 예외를 throw합니다. 따라서 doThrow(). when (..). method (...)를 사용해야합니다.

+1

질문의 두 번째 부분에서는, (...). thenReturn이 실제로 메서드를 호출 할 때를 말했습니다. 나는 스파이 물건들에 대해서만 진실이라고 생각하고 조롱 된 물건들에 대해서는 (모의를 사용해서) 생각하지 않는다. –

2

첫 번째 예는 디자인과 동일하므로 자세한 내용은 아래 링크를 참조하십시오. 스터브 번 더 when(mockObj.method(param1,param2)).thenThrow(ExceptionTwo.class); 등록하는 동안 두 번째 예에서

https://static.javadoc.io/org.mockito/mockito-core/2.11.0/org/mockito/Mockito.html#stubbing_consecutive_calls

는 예외가 발생 하였다. 명세서 mockObj.method(param1, param2);이 아닌 것이 중요합니다.

두 번째 when.thenThrow 문이 실행되는 동안 실제 메서드 호출이있을 수 있습니다. 후속 호출에 대해 다른 예외를 원한다면 문서가 here을 언급, 당신은 하나 개의 문장 첫 번째 경우에 when(mockObj.method(param1, param2)).thenThrow(ExceptionOne.class, ExceptionTwo.class);

+0

첫 번째 (..). thenThrow() 문에 실제로 예외를 던지는 두 번째 throw 문임을 확인해 주셔서 감사합니다. –