SpringBoot Junit bean 自动装配

2024-01-31

我尝试将 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 的可见性之外,因此不会自动连接任何内容。

Spring Boot 具有广泛的测试支持,并且还可以用模拟替换 bean,请参阅测试部分 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-mocking-beansSpring Boot 参考指南。

要修复它,请使用框架而不是围绕它。

  1. Replace @Mock with @MockBean
  2. Replace @InjectMocks with @Autowired
  3. 删除您的设置方法

显然,您只需要 SOAP 存根的模拟(因此不确定您需要模拟什么)LottoClient for).

像这样的事情应该可以解决问题。

@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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot Junit bean 自动装配 的相关文章

随机推荐