johncol
johncol

Reputation: 614

MapStruct mapper not injected in Spring Unit Tests

I'm using one mapper generated with MapStruct:

@Mapper
public interface CustomerMapper {
   Customer mapBankCustomerToCustomer(BankCustomerData bankCustomer);
}

The default component model is spring (set in pom.xml)

<compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>

I have a service in which I inject the customer mapper and works fine when I run the application

@Autowired
private CustomerMapper customerMapper;

But when I run unit tests that involves @SpringBootTest

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class SomeControllerTest {

    @Mock
    private SomeDependency someDependency;

    @InjectMocks
    private SomeController someController;

    @Test
    public void shouldDoSomething() {
        ...
    }

}

I get an org.springframework.beans.factory.UnsatisfiedDependencyException

Unsatisfied dependency expressed through field 'customerMapper'

Upvotes: 5

Views: 11219

Answers (2)

dwilda
dwilda

Reputation: 83

I followed this answer and my problem was solved as quickly as I pasted proposed lines in my build.gradle file

Upvotes: 1

Filip
Filip

Reputation: 21423

As you are running your tests via the IDE there are 2 possibilities:

  1. Eclipse or IntelliJ is picking up the Annotation Processors, you need to set them up correctly.
  2. Eclipse or IntelliJ does not pick up the compiler options from the maven compiler

To rule out the possibilities do the following for each:

  1. Make sure the IDE is configured to run APT. Have a look here how you can set it up. Run a build from the IDE and check if there are generated mapper classes
  2. If there are they are most probably generated with the default component model. To solve this you have two options:
    1. Use @Mapper(componentModel = "spring"). I personally prefer this option as you are IDE independent. You can also use a @MapperConfig that you can apply
    2. Configure the IDE with the annotation options. For IntelliJ add the compiler argument in Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors, there is a section called Annotation Processor Options there add mapstruct.defaultComponentModel as option name and spring as value. I am not sure how to do it for Eclipse

Upvotes: 0

Related Questions