我有以下课程设置。
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
and Child
类注入它们的属性?
Thanks!!
只需这样做:
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 应该做正确的事。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)