How can I inject mocks into a bean that requires constructor arguments

Viewed 343

I have a prototype spring bean that has some injected dependencies and also have some constructor arguments.

public BeanA {

  @Inject private BeanB beanB;

  private String arg;

  public BeanA(String arg) {
    this.arg = arg;
  }

public void methodToTest() {
  // ...
  // ...
  // ...
  }

}

I want to unit test this class, mocking my injected BeanB.

Usually, I'd use @InjectMocks to start my mocks inside BeanA.

How can I achieve this? So far, I don't want to inject BeanB in the constructor as it would mix business arguments and dependencies.

2 Answers

Spring has a ReflectionTestUtils that can be used to inject mocks into fields.

@ExtendWith(MockitoExtension.class)
class BeanATest {

  private BeanA beanA;

  @Mock private BeanB beanB;

  void setUp(String arg) {
    beanA = new BeanA(arg);
    ReflectionTestUtils.setField(beanA, "beanB", beanB);
  }

  @Test
  void test() {
    String arg = "arg";
    setUp(arg);

    // ...
    beanA.methodToTest();
    // ...
  }

}

Related