Jaxb2Marshaller Mock Bean становится нулевым JUNIT5 - PullRequest
0 голосов
/ 03 мая 2020

Я пытаюсь написать JUNIT для метода. Умею издеваться над всеми остальными бобами, кроме Jaxb2Marshaller. В фактическом методе я получаю исключение нулевого указателя для Jaxb2Marshaller. Другие компоненты доступны из того же класса конфигурации. Почему недоступен только компонент Jaxb2Marshaller.

ИСПЫТАТЕЛЬНЫЙ КЛАСС

@SpringBootTest
@ActiveProfiles("test")
class EPSGCFundAndActivateAPIClientTest {

    @Autowired
    EPSGCFundAndActivateAPIClient epsgcFundAndActivateAPIClient;

    @MockBean
    @Qualifier("paymentServiceRestTemplate")
    RestTemplate paymentServiceRestTemplate;

    @MockBean
    Jaxb2Marshaller jaxb2Marshaller;

    @Test
    void consume() throws JAXBException {
        String input = ""; 
        //I cannot mock the jaxb2Marshaller marshal call . Because its void.
        epsgcFundAndActivateAPIClient.consume(input);
    }

}

КЛАСС КОНФИГУРАЦИИ

@Configuration
@DependsOn({"otsProperties"})
public class BeanConfiguration {

    @Bean
    public Jaxb2Marshaller jaxb2Marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        Map<String, Object> properties = new HashMap<>();
        properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setMarshallerProperties(properties);
        return marshaller;
    }
    @Bean
    public RestTemplate paymentServiceRestTemplate() {
        final RestTemplateBuilder builder =
                new RestTemplateBuilder().basicAuthentication("ABC", "123456");
        builder.messageConverters(new Jaxb2RootElementHttpMessageConverter());
        return builder.build();
    }

}

ФАКТИЧЕСКИЙ КЛАСС

@Component("epsGCFundAndActivateAPIClient")
public class EPSGCFundAndActivateAPIClient  {

    @Autowired
    @Qualifier("paymentServiceRestTemplate")
    RestTemplate paymentServiceRestTemplate;

    @Autowired
    Jaxb2Marshaller jaxb2Marshaller;

    @Override
    public PaymentServiceResponse consume(Input input) {
      StringWriter sw = new StringWriter();
        jaxb2Marshaller.createMarshaller().marshal(input.getPayload(),sw); // Getting null pointer Exception for jaxb2Marshaller

        paymentServiceRestTemplate.methodCall(sw); // If i comment out the above line this method is getting called successfully. Means paymentServiceRestTemplate is available.

    } 
}

1 Ответ

1 голос
/ 03 мая 2020

Я не думаю, что вы получите NullPointerException, потому что jaxb2Marshaller равно нулю, а скорее потому, что выражение jaxb2Marshaller.createMarshaller() вернуло значение null, и дальнейший вызов marshal - это тот, который действительно выбрасывает исключение.

Если это действительно так, то это происходит потому, что вы не издевались над вызовом createMarshaller. Вы должны высмеять jaxb2Marshaller.createMarshaller(), чтобы вернуть маршаллера:


@Test
void consume() throws JAXBException {
    when(jaxb2Marshaller.createMarshaller()).thenReturn(whateverYouNeed);

    String input = ""; 
    //I cannot mock the jaxb2Marshaller marshal call . Because its void.
    epsgcFundAndActivateAPIClient.consume(input);

}
...