ima.technophyle
ima.technophyle

Reputation: 667

Spring Boot : JAXBElement null pointer exception

I am totally new to Junit 5 and Mockito framework. Now I am trying to implement JUnit test cases for the function. Can someone help in Mocking, because the below test implementation throws a NullPointerException at the specified line.

Class XYZ{

       @Autowired
       private SoapCall soapCall;

       public void validate(){
 
                 //code....

            JAXBElement <SubDTO> jax = (JAXBElement <Sub_DTO>) soapCall.callSoapService(val1, val2, val3, val4, val5);
 
            SubDTO  response = jax.getValue();  // Getting null pointer exception while Unit testing at this line   

        }
}

Unit Testing

Class TestValid{

   @Mock
   SoapCall soapCall;

   @InjectMocks
   XYZ xyzzy;

   @BeforeEach
   void setUp(){
      MockitoAnnotations.initMocks(this);
   }

   @Test
   public void test1(){
        SubDTO dto= new SubDTO("a","b","c");

        JAXBElement<SubDTO> jax = new JAXBElement <> (any(), any(), any());

        jax.setValue(dto)            

   Mockito.when(soapCall.callSoapService(any(),any(),any(),anyInt(),anyInt())).thenReturn( jax );

        Assertions.assertDoesNotThrow(()->xyz.validate());
   }
}

Upvotes: 0

Views: 277

Answers (1)

Luke Woodward
Luke Woodward

Reputation: 64969

This line looks odd to me:

        JAXBElement<SubDTO> jax = new JAXBElement <> (any(), any(), any());

any() is a matcher and is only used when setting up mocking or during verification. It always returns null.

Basically, you are writing code that will do the same as this:

        JAXBElement<SubDTO> jax = new JAXBElement <> (null, null, null);

Instead of passing in null values, pass in a QName, a class and an instance of that class as the arguments to the JAXBElement constructor.

However, I don't get a NullPointerException when I attempt to run your code. I get an IllegalArgumentException at the line above, complaining about the null values.

Upvotes: 1

Related Questions