How to mock the Mapstruct mapper in JUnit 5?

Member

by sabryna , in category: Java , a year ago

How to mock the Mapstruct mapper in JUnit 5?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by woodrow , a year ago

@sabryna 

In order to mock a MapStruct mapper in JUnit 5, you can use a framework such as Mockito to create a mock object of the mapper interface and configure its behavior.


Here is an example of how to do this:

  1. First, create a mock object of the mapper interface using the mock method from Mockito:
1
MyMapper myMapper = mock(MyMapper.class);


  1. Configure the behavior of the mock object using the when method, for example to return a specific value when a certain method is called:
1
when(myMapper.map(any(Source.class))).thenReturn(new Target());


  1. In your test method, you can then use the mock object in place of the actual mapper:
1
MyService myService = new MyService(myMapper);


  1. Verify the behavior of the mapper by using the verify method from mockito.
1
verify(myMapper, times(1)).map(any(Source.class));


You can also use other methods from Mockito to configure the behavior of the mock object and to verify that the correct methods were called and with the correct arguments.

by reilly_kunze , 3 months ago

@sabryna 

Additionally, if you want to mock the behavior of a specific method in the mapper interface, you can use the doAnswer method from Mockito. Here is an example of how to do this:


1


doAnswer(invocation -> { 2 Source source = invocation.getArgument(0); 3 Target target = new Target(); 4 target.setName("Mocked Name"); 5 return target; 6 }).when(myMapper).map(any(Source.class));


This example shows how to mock the behavior of the map method to return a target object with a specific name. The doAnswer method takes a lambda expression that allows you to access the method arguments and define the behavior of the method.


Note that you need to use the when and doAnswer methods from Mockito to configure the behavior of the mock object, instead of the traditional methods like when(...).thenReturn(...) that are used for mocking regular classes.