提问者:小点点

SpringBoot JUnit bean自动线


我尝试将 junit 测试写入我的服务。我在我的项目中使用Spring引导 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();
    }
}

共1个答案

匿名用户

当然,您的依赖关系将是<code>null</code>,因为<code>@InjectMocks</code<您正在创建一个新实例,在Spring的可见性之外,因此不会自动连接任何东西。

Spring Boot有广泛的测试支持,关于用模拟替换beans,请参阅《Spring Boot参考指南》的测试部分。

要解决这个问题,请使用框架,而不是绕过它。

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

显然,您只需要SOAP存根的模拟(因此不确定您需要为Lotto客户端模拟什么)。

像这样的东西应该可以解决问题。

@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();