4

I have many different SpringBoot tests running. So far the auto configuration slices were really helpful, especially in combination with @MockBean.

But in my current test no such slice fits and booting up the complete context using @SpringBootTest is too slow.

Is there a way to manually set the tip of the object tree to be started with and from there spring autowires all needed beans? Or is there a way to set all needed beans manually?

In my specific case i want to test a MapStruct generated mapper (using componentModel = "spring") this mapper uses two other mappers, each injecting a service to do their work.

The services are provided via @MockBean:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductResponsibleUnitMapperTest {

    @Autowired
    private PRUMapper mapper;

    @MockBean
    private TradingPartnerService tradingPartnerService;

    @MockBean
    private ProductHierarchyService productHierarchyService;

    @Test
    public void mapForthAndBack(){
      //works but takes ages to boot
    }

}

I could not use constructor injection on the mappers (for the services) because MapStruct won't generate correct implementations.

How to get a Spring-Context only containing the needed beans?

dermoritz
  • 12,519
  • 25
  • 97
  • 185

1 Answers1

2

I found one way by explicitly declaring all implementation used:

@SpringBootTest(classes = {ProductResponsibleUnitMapperImpl.class, LegalEntityMapperImpl.class, ProductHierarchyMapperImpl.class}) 

For more complex setups it will be cumbersome and also dangerous to declare generated classes.

I am still searching for a better cleaner way to let Spring decide what classes needed. It should be possible to set the class in hand and let Spring decide what classes needed and to be instantiated.

dermoritz
  • 12,519
  • 25
  • 97
  • 185
  • If you don't test the actual MapperImpl, how about just mocking it: with @SpringBean ProductResponsibleUnitMapper hedgingProfileMapper = Mock() – Vlad Topala Jun 28 '19 at 08:16
  • 1
    i need these mappers, what they are doing. The point is that i could cut out a specific test frame with this. – dermoritz Jun 28 '19 at 08:50
  • I understand. I had the same issue with an `@DataMongoTest` but fortunately I was not testing code affected by the MapperImpl. – Vlad Topala Jun 28 '19 at 09:07