title: Spring Boot: How to test a class which is using gson object using autowiring
body: <p>I am new to JUnit and unit testing in java. I am having an issue while testing my code. Any help is appreciated.</p>
  <p>My java class: <code>AService.java</code></p>
  <pre><code>@Service
  public class AService {
  
      @Autowired
      private ServiceB serviceB;
  
      @Autowired
      private Gson gson;
  
      public MyEntity getEntity() {
          String jsonResponse = serviceB.getResponse();
          return gson.fromJson(jsonResponse, MyEntity.class);
      }
  }
  </code></pre>
  <p>My test class: <code>AServiceTest.java</code></p>
  <pre><code>@ExtendWith(MockitoExtension.class)
  public class AServiceTest {
  
      @Mock
      private ServiceB serviceB;
  
      @Autowired
      private Gson gson;
  
      @InjectMocks
      private AService aService;
  
      @Test
      public void getEntityTest() {
          String serviceBResponse = &quot;{\&quot;id\&quot;:55,\&quot;name\&quot;:\&quot;My entity\&quot;,\&quot;address\&quot;:\&quot;XYZ\&quot;}&quot;;
          when(serviceB.getResponse()).thenReturn(serviceBResponse);
  
          MyEntity entity = aService.getEntity();
          assertEquals(&quot;My entity&quot;, entity.getName());
      }
  }
  </code></pre>
  <p>This is giving NullPointerException because <code>gson</code> object is not getting initialized. Also we can not mock <code>gson</code> as <code>Gson</code> class is <code>final</code>.</p>
  <p>How can I test this code. I am using <strong>spring boot</strong> and <strong>junit5.</strong></p>