代码之家  ›  专栏  ›  技术社区  ›  JiKra

Mockito处于调试模式,断点导致返回值的类型错误

  •  1
  • JiKra  · 技术社区  · 7 年前

    这里有一个简单的片段。

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

    那么,问题在哪里?

    0 回复  |  直到 7 年前
        1
  •  1
  •   barbsan Cibi    6 年前

    你在用idea调试吗?idea调试器可能会中断存根过程。

    首选项->生成、执行、部署->调试器->数据视图->Java ,取消 启用“toString()”对象视图 复选框