我尝试将junit测试写入我的服务。我在我的项目spring-boot 1.5.1中使用。一切正常,但是当我尝试自动装配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(); } }
当然null,由于@InjectMocks您正在创建一个新实例,因此依赖关系将在Spring的可见范围之外,因此不会自动进行连线。
null
@InjectMocks
Spring Boot提供了广泛的测试支持,并且可以用模拟代替bean,请参阅Spring Boot参考指南的“测试”部分。
要对其进行修复,请使用框架而不是围绕框架。
@Mock
@MockBean
@Autowired
同样显然,您只需要为SOAP存根提供一个模拟(因此不确定对于LottoClientfor来说需要模拟什么)。
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();