0

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. my goal would be to invoke the 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?

2 Answers 2

1

Try this

when(mapper.mapToDTO(Mockito.eq(dto), Mockito.any(ElementHandler.class))).thenThrow( new MappingFailureException()); 
Sign up to request clarification or add additional context in comments.

Comments

1

Considering mapper is mocked...

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)

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.