spring-bootmockitospring-boot-test

SpringBootTest - classes - Mock a required constructor argument


We are using SpringBootTest for Integration testing.

Let us say for example that we have a class : ClassWithManyConstructorArgs with one Required Constructor Argument (another class, DependencyA) and no default constructor.

Example : public ClassWithManyConstructorArgs(DependencyA a){ }

Our Integration test is configured as :

@SpringBootTest ( classes = [ClassWithManyConstructorArgs::class] )

I need to provide mocked implementations of the DependencyA class. How can I do that? What is the syntax to tell the system to initialize the ClassWithManyConstructorArgs using mocked DependencyA object?


Solution

  • Assume we have two beans: ServiceA and ServiceB.

    ServiceA depends on ServiceB. for testing,

    1. we load ServiceA into our test applicationContext(@SpringBootTest(classes = {ServiceA.class})).
    2. use @Autowired on ServiceA for injecting the real instance that need to be tested, use @MockBean on ServiceB for creating a mocked bean that need to support the testing.
    3. now we can test our methods in ServiceA with the mocked bean serviceB.

    here's the code:

    @SpringBootTest(classes = {ServiceA.class})
    public class ServiceATest {
      @MockBean
      private ServiceB serviceB;
    
      @Autowired
      private ServiceA serviceA;
    
      @Test
      void testMethodA() {
        serviceA.methodA();
      }
    }