简体   繁体   English

如何在Mockito中模拟方法参数

[英]How to mock method parameter in Mockito

I have a method what I want to test. 我有一种方法要测试。 This method can throw an exception. 此方法可以引发异常。

mapper.mapToDTO(fragment.getDTO(), new ElementHandler());

I want to test, that what happens after the Exception. 我想测试一下,在异常之后会发生什么。 So I made a Mocked test: 所以我做了一个模拟测试:

when(mapper.mapToDTO(dto, Mockito.any(ElementHandler.class))).thenThrow(
            new MappingFailureException());

Unfortunatelly this Mocking is not good. 不幸的是,这个模拟不好。 I also know that the Mockito.any part is not good. 我也知道Mockito.any部分不好。 my goal would be to invoke the MappingFailureException 我的目标是调用MappingFailureException

How can I map an Object of a type of a class, that my Exception will be thrown if any type of ElementHandler class is given as a parameter? 我如何映射一个类类型的对象,如果给定任何类型的ElementHandler类作为参数,都会抛出我的异常?

Try this 尝试这个

when(mapper.mapToDTO(Mockito.eq(dto), Mockito.any(ElementHandler.class))).thenThrow(
        new MappingFailureException());

Considering mapper is mocked... 考虑到mapper被嘲笑了...

Mapper mapper = mock(Mapper.class);

Yo can do something like this to try (it should be the same as your test) 您可以做这样的尝试(它应该与您的测试相同)

doThrow(new MappingFailureException()).when(mapper).mapToDTO(dto, Mockito.any(ElementHandler.class));

If not you can build your custom answer with mockito (in the example it returns an String but change it to the return value of mapToDTO) 如果没有,您可以使用mockito构建您的自定义答案(在该示例中,它返回一个String,但将其更改为mapToDTO的返回值)

when(mapper.mapToDTO(dto, Mockito.any(ElementHandler.class))).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
      throw new MappingFailureException();
    }
  });

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM