繁体   English   中英

SpringBoot Junit bean自动接线

[英]SpringBoot Junit bean autowire

我尝试将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();
    }
}

当然,由于您正在创建新实例的@InjectMocks (在Spring的可见范围之外),因此您的依赖关系将为null ,因此不会自动进行连线。

Spring Boot提供了广泛的测试支持,并且可以用模拟代替bean,请参阅Spring Boot参考指南的“测试”部分

要对其进行修复,请使用框架而不是围绕框架。

  1. @MockBean替换@Mock
  2. @Autowired替换@InjectMocks
  3. 删除设置方法

同样显然,您只需要对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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM