我正在使用 Mockito 为 Spring 应用程序编写单元测试,以下是服务类的单元测试。
服务等级:
@Service
class MyServiceImpl implements MyService{
@Autowired
private ExternalService externalService;
MyServiceImpl () {
int value = externalService.getValues();
}
}
正如您所注意到的,我使用 Autowired 服务类“ExternalService”中的方法初始化构造函数内的实例变量。
测试类:
public class LotteryServiceImplTest {
@InjectMocks
private MyServiceImpl myService;
@Mock
private ExternalService externalService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetLotteryResult() {
//test specific code
}
}
当我运行测试时出现错误:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'value' of type 'MyServiceImpl'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
当测试对象的构造函数依赖于mock时,如何在注入(inject)测试对象之前创建mock服务?
最佳答案
问题在于您在 MyServiceImpl 类中注入(inject)和使用ExternalService 依赖项的方式。 @Autowired 由 BeanPostProcessor () 处理,该 BeanPostProcessor () 在 bean 实例化后运行。因此,externalService 引用的值仅在构造函数运行后才初始化。所以你不能在你的构造函数中使用它,因为此时它仍然为空;
您可以通过移动此行 int value = externalService.getValues(); 来解决此问题从构造函数到您的业务方法。
如果你想在启动时初始化一次值,你可以像这样使用 @PostConstruct 初始化回调
@Service
class MyServiceImpl implements MyService{
@Autowired
private ExternalService externalService;
private int value;
MyServiceImpl () {
}
@PostConstruct
public void initValue(){
value = externalService.getValues();
}
}
关于java - 从构造函数中初始化实例变量时出现 Mockito 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36056096/