我正在爲使用Mockito的彈簧應用程序編寫單元測試,以下是服務類的單元測試。Mockito初始化構造器內的實例變量時出錯
服務類:
@Service
class MyServiceImpl implements MyService{
@Autowired
private ExternalService externalService;
MyServiceImpl() {
int value = externalService.getValues();
}
}
正如你可以看到我使用初始化從名爲ExternalService服務類,這是自動裝配Autowired的方法構造函數中的一個實例變量。
測試類:
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
我怎麼能注入測試對象之前創建模擬服務當測試對象的構造取決於模擬?