我有下面的 class 设置。
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
会为空。如果使用测试设置中的Child
类的构造函数,则Base
类中的字段会变成null
。我知道关于字段注入的所有争论都是邪恶的,但是我更想知道是否有一种解决方法,而无需更改
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应该做正确的事。