Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot test minimal test slice or manual configuration

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?

like image 243
dermoritz Avatar asked Oct 27 '25 11:10

dermoritz


1 Answers

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.

like image 51
dermoritz Avatar answered Oct 29 '25 01:10

dermoritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!