【发布时间】:2016-07-03 12:54:57
【问题描述】:
我正在使用 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时,如何在注入测试对象之前创建mock服务?
【问题讨论】:
标签: java spring unit-testing mockito