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

获取“InvalidUseofMatcherException”,即使它使用正确

  •  1
  • kramsiv94  · 技术社区  · 6 年前

    @Mock
    ObjectMapper objectMapper = new ObjectMapper();
    

    然后我写了一些嘲弄的逻辑,声称我做错了:

    Mockito.when(objectMapper.writeValueAsString(Mockito.anyObject())).thenThrow(JsonProcessingException.class);
    

    我哪里出错了?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Nkosi    6 年前

    匹配方法,如 anyObject() eq() 不要 anyObject() , 等式()

    我的建议是 any()

    例如

    @Test
    public void TestObjectMapper() {
        //Arrange
        ObjectMapper objectMapper = mock(ObjectMapper.class);
        when(objectMapper.writeValueAsString(any()))
            .thenThrow(new JsonProcessingException());
    
        //...
    }
    
        2
  •  0
  •   Ramachandra A Pai    6 年前

    我将@InjectMocks用于被测试的类,而@Mock用于自动创建和注入Mock。这对我来说非常好。

    像这样:

    @RunWith(MockitoJUnitRunner.class)
    public final class ClassTest{
    
        @InjectMocks
        private ClassUnderTest objectOfClass;
    
        @Mock 
        private ObjectMapper objectMapper = new ObjectMapper();
    
        @Test (expected = JsonProcessingException.class)
        public void testMethod() {
            when(objectMapper.writeValueAsString(anyObject()))
           .thenThrow(JsonProcessingException.class);
        }
    }
    

    when(mock.doSomething(any(), someMock)).thenReturn(something); // This can generate the exception.
    

    when(mock.doSomething(any(),eq(someMock))).thenReturn(something); // Here we use eq matcher instead of simply passing the mock