How to write Junit test for mapstruct abstract mapper injected via Spring
Addition to @TheBakker's answer: as a lighter alternative to @SpringBootTest
you can use @ContextConfiguration
, if you do not require the whole SpringBoot stack. His example would look like this:
@ExtendWith(SpringExtension.class) // JUnit 5
@ContextConfiguration(classes = {
ConfigurationMapperImpl.class,
SubMapper1Impl.class,
SubMapper2Impl.class
})
public class ConfigurationMapperTest {
...
With JUnit 4 use annotation RunWith
instead of ExtendWith
:
@RunWith(SpringRunner.class) // JUnit 4
...
In response to @Richard Lewan comment here is how I declared my test class for the abstract class ConfigurationMapper using 2 subMappers
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ConfigurationMapperImpl.class, SubMapper1Impl.class, SubMapper2Impl.class})
public class ConfigurationMapperTest {
You use the Impl
generated classes in the SpringBootTest
annotation and then inject the class you want to test:
@Autowired
private ConfigurationMapper configurationMapper;
Let me know if you need more info, but from there it's straightforward. I didn't mock the subMapper, as it was better for me to test all the mapping process at once.