gpt4 book ai didi

intellij-idea - Mockito 处于 Debug模式,断点结果为 WrongTypeOfReturnValue

转载 作者:行者123 更新时间:2023-12-04 01:50:49 26 4
gpt4 key购买 nike

有这个简单的片段。

@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"));
}
}

现在,当我运行测试时,它运行正常,但是当我在 Debug模式下运行它同时断点在 when...thenReturn... 模拟并使用 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.

但是,如果我使用以下 oneliner 而不是 twoliner,则可以。没有返回错误。
when(someDependency.getSomeInt(anyString())).thenReturn(Optional.of(111));

那么,问题出在哪里呢?

最佳答案

你在用idea调试吗?想法调试器可能会破坏 stub 过程。

转至 首选项 -> 构建、执行、部署 -> 调试器 -> 数据 View -> Java , 取消 启用“toString()”对象 View 复选框

关于intellij-idea - Mockito 处于 Debug模式,断点结果为 WrongTypeOfReturnValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com