这里有一个简单的片段。
@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"));
}
}
现在,当我运行测试时,它运行正常,但是当我在调试模式下运行它时,断点处于打开状态时…然后返回。。。模拟和使用
step over
,引发以下错误。
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.
但是,如果我用一行而不是二行,那没关系。没有返回错误。
when(someDependency.getSomeInt(anyString())).thenReturn(Optional.of(111));
那么,问题在哪里?