There is this simple snippet.
@Component
public class SomeDependency {
public Optional<Integer> getSomeInt(String string) {
return Optional.of(1);
}
}
@Component
public class SomeService {
@Autowired
private SomeDependency someDependency;
public String someMethod(String string) {
return String.valueOf(someDependency.getSomeInt(string).get());
}
}
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@Mock
private SomeDependency someDependency;
@InjectMocks
private SomeService someService;
@Test
public void test() {
when(someDependency.getSomeInt(anyString()))
.thenReturn(Optional.of(111));
String value = someService.someMethod("test");
assertThat(value, is("111"));
}
}
Now, when I run the test, it goes OK, but when I run it in debug mode while having breakpoint on when...thenReturn... mock and use step over, following error is thrown.
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Optional cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
But, if I use following oneliner instead of the twoliner, it's OK. No error returned.
when(someDependency.getSomeInt(anyString())).thenReturn(Optional.of(111));
So, where is the problem?