응용 프로그램을 unittest하려면 Mockito를 배우는 데 어려움을 겪고 있습니다. 아래 방법 메신저의 예는 현재Unittest with Mockito - 무시 메서드 호출
public boolean validateFormula(String formula) {
boolean validFormula = true;
double result = 0;
try {
result = methodThatCalculatAFormula(formula, 10, 10);
} catch (Exception e) {
validFormula = false;
}
if (result == 0)
validFormula = false;
return validFormula;
}
이 방법은 내가 validateFormula
을 유닛 테스트 할 때 전화하지 않으려는 같은 클래스, methodThatCalculatAFormula
, 다른 메소드를 호출을 테스트하기 위해 노력하고있다.
이 문제를 테스트하려면이 방법이 methodThatCalculatAFormula
이 반환하는 방식에 따라 어떻게 작동하는지보고 싶습니다. result
이 0 일 때 false
을 반환하고 어떤 숫자라도 유효하면 0을 반환하므로 실제 methodThatCalculatAFormula
메서드를 실행하지 않고이 반환 값을 시뮬레이션하고 싶습니다.
public class FormlaServiceImplTest {
@Mock
FormulaService formulaService;
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testValidateFormula() {
`//Valid since methodThatCalculatAFormula returns 3`
when(formulaService.methodThatCalculatAFormula(anyString(),anyDouble(),anyDouble(),anyBoolean())).thenReturn((double)3);
assertTrue(formulaService.validateFormula("Valid"));
//Not valid since methodThatCalculatAFormula returns 0
when(formulaService.methodThatCalculatAFormula(anyString(),anyDouble(),anyDouble(),anyBoolean())).thenReturn((double)0);
assertFalse(formulaService.validateFormula("Not Valid"));
}
그러나 내 assertTrue
이 false
입니다 위의 코드를 실행하면
나는 다음과 같은 작성했습니다. 나는 내 모의 설치에서 뭔가 잘못했다고 짐작했다. 어떻게 실제로 위의 메서드를 호출하지 않고 methodThatCalculatAFormula
의 반환 값을 시뮬레이션하여 위의 메서드를 테스트 할 수 있습니다.
spy 명령이 정상적으로 작동했습니다. 내가 이해할 수 있듯이, 그것은 모의 인 것만을 테스트 할 수있게 해주는 지정된 메소드를 모의합니다. –
예, (spy.method()). doReturn (result)이 아닌 경우 doReturn (result) .when (spy) .method() 구문을 사용해야합니다. 후자는 모의 메소드를 정의하기 전에 원래의 메소드를 호출 할 것이기 때문에 작동하지 않을 것이다. – rcomblen
그래, 내가 찾은 UnfinishedStubbException을 얻었 기 때문에 그 해답을 발견했다. –