我尝试将junit测试写入我的服务。 我在我的项目spring-boot 1.5.1中使用。一切正常,但是当我尝试autowire bean(在AppConfig.class中创建)时,它给了我NullPointerException。我几乎尝试了一切。
这是我的配置类:
@Configuration
public class AppConfig {
@Bean
public DozerBeanMapper mapper(){
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomFieldMapper(new CustomMapper());
return mapper;
}
}
和我的测试班:
@SpringBootTest
public class LottoClientServiceImplTest {
@Mock
SoapServiceBindingStub soapServiceBindingStub;
@Mock
LottoClient lottoClient;
@InjectMocks
LottoClientServiceImpl lottoClientService;
@Autowired
DozerBeanMapper mapper;
@Before
public void setUp() throws Exception {
initMocks(this);
when(lottoClient.soapService()).thenReturn(soapServiceBindingStub);
}
@Test
public void getLastResults() throws Exception {
RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
when(lottoClient.soapService().getLastWyniki(anyString())).thenReturn(expected);
LastResults actual = lottoClientService.getLastResults();
有人能告诉我什么是错的吗?
错误日志:
java.lang.NullPointerException
at pl.lotto.service.LottoClientServiceImpl.getLastResults(LottoClientServiceImpl.java:26)
at pl.lotto.service.LottoClientServiceImplTest.getLastResults(LottoClientServiceImplTest.java:45)
这是我的服务:
@Service
public class LottoClientServiceImpl implements LottoClientServiceInterface {
@Autowired
LottoClient lottoClient;
@Autowired
DozerBeanMapper mapper;
@Override
public LastResults getLastResults() {
try {
RespLastWyniki wyniki = lottoClient.soapService().getLastWyniki(new Date().toString());
LastResults result = mapper.map(wyniki, LastResults.class);
return result;
} catch (RemoteException e) {
throw new GettingDataError();
}
}
答案 0 :(得分:4)
当然,您的依赖关系将是null
,因为@InjectMocks
您正在创建一个新实例,超出了Spring的可见性,因此没有任何内容会自动连接。
Spring Boot具有广泛的测试支持以及用模拟替换bean,请参阅Spring Boot参考指南的the testing section。
要修复它,请使用框架而不是它。
@Mock
替换为@MockBean
@InjectMocks
替换为@Autowired
显然你只需要一个模拟SOAP存根(所以不确定你需要为LottoClient
模拟什么)。
这样的事情应该可以解决问题。
@SpringBootTest
public class LottoClientServiceImplTest {
@MockBean
SoapServiceBindingStub soapServiceBindingStub;
@Autowired
LottoClientServiceImpl lottoClientService;
@Test
public void getLastResults() throws Exception {
RespLastWyniki expected = Fake.generateFakeLastWynikiResponse();
when(soapServiceBindingStub.getLastWyniki(anyString())).thenReturn(expected);
LastResults actual = lottoClientService.getLastResults();