5

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'

MWiesner
  • 8,868
  • 11
  • 36
  • 70
johncol
  • 584
  • 1
  • 7
  • 13
  • Is this happening when invoking the test via an IDE, via Maven or both? – Filip Jun 02 '17 at 16:51
  • If it's IDE-only, my guess would be that _target/generated-sources_ isn't added as a source folder in the IDE project. – Gunnar Jun 02 '17 at 21:09
  • I only run the tests using the IDE, but I did add the generated-sources folder as a source folder, otherwise my application would have not run. – johncol Jun 04 '17 at 01:29

2 Answers2

1

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

dwilda
  • 83
  • 2
  • 12
0

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
Filip
  • 19,269
  • 7
  • 51
  • 60