Spring: unit test for class that has both field & constructor injection

好久不见. 提交于 2021-02-19 02:46:05

问题


I have below setup of classes.

class Base {
   @Autowired
   private BaseService service; //No getters & setters
   ....
}

@Component
class Child extends Base {
  private final SomeOtherService otherService;

  @Autowired   
  Child(SomeOtherService otherService) {
     this.otherService = otherService;
  }
}

I am writing a unit test for the Child class. If I use @InjectMocks then the otherService comes out to be null. If I use, the constructor of Child class in the setup of the test, then the fields in Base class comes out to be null.

I know all the arguments about field injection being evil, but I am more interested in knowing if there is a way to solve this without changing the way Base and Child classes injects their properties?

Thanks!!


回答1:


Just do this:

public class Test {
    // Create a mock early on, so we can use it for the constructor:
    OtherService otherService = Mockito.mock(OtherService.class);

    // A mock for base service, mockito can create this:
    @Mock BaseService baseService;

    // Create the Child class ourselves with the mock, and
    // the combination of @InjectMocks and @Spy tells mockito to
    // inject the result, but not create it itself.
    @InjectMocks @Spy Child child = new Child(otherService);

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
    }
}

Mockito should do the right thing.



来源:https://stackoverflow.com/questions/43045357/spring-unit-test-for-class-that-has-both-field-constructor-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!