我有下面的课程设置.
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;
}
}
我正在为Child类编写单元测试.
如果我使用@InjectMocks,则otherService结果为null.如果使用测试设置中的Child类的构造函数,则Base类中的字段显示为空.
我知道关于字段注入的所有争论都是邪恶的,但是我更想知道是否有一种方法可以解决此问题,而无需更改Base和Child类注入其属性的方式?
谢谢!!
解决方法:
只要这样做:
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应该做正确的事.