Mock local variable inside method with mockite and spring boot

Asked

Viewed 481 times

0

I’m trying to simulate the return of a method on a local variable, but it’s always null, showing java.lang.Nullpointerexception

I have the following code within a @service:

@Service
@AllArgsConstructor
public class VideoEncodingService {
  private final MainService mainService;
  @Value("${bucket.videos.aws.s3}")
  private String bucketS3;

  @Value("${accessKey.acess.bucket}")
  private String accessKeyS3;

  @Value("${secretKey.acess.bucket}")
  private String secretKeyS3;

  @Value("${bit.movin.url.api.output.s3}")
  private String urlEndpointOutputS3;

public void createOutputS3(Config cf) {
    // encoding/outputs/s3
    OutputS3DTO os3 = mainService.returnObject(urlEndpointOutputS3,
        new OutputS3DTO(bucketS3, accessKeyS3, secretKeyS3), new TypeReference<OutputS3DTO>() {});
    cf.setIdOutputS3(os3.getId());
  }
}
@Service
@AllArgsConstructor
public class MainService {

  private final RestTemplate restTemplate;


  private final ObjectMapper mapper;

  @Value("${bit.movin.url}")
  private String urlBaseBitMovin;

  @Value("${bit.movin.api.key}")
  private String apiKey;

  protected <T> String post(String urlApi, T object) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("X-Api-Key", apiKey);
    HttpEntity<?> request = new HttpEntity<>(getJSON(object), headers);
    return restTemplate.postForObject(urlBaseBitMovin + urlApi, request, String.class);
  }

  private <T> String getJSON(T instance) throws RuntimeException {
    try {
      return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(instance);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @SuppressWarnings("unchecked")
  public <T> T returnObject(String endpoint, T instance, TypeReference<T> typeReference)
      throws RuntimeException {
    try {
      String jsonResult = post(endpoint, instance);
      JSONObject jSONObject = new JSONObject(jsonResult);
      JSONObject resultObject;
      resultObject =
          jSONObject.getJSONObject(KEY_DATA_BIT_MOVIN).getJSONObject(KEY_RESULT_BIT_MOVIN);
      if (resultObject != null) {
        return (T) mapper.readValue(resultObject.toString(), instance.getClass());
      }
    } catch (Exception e) {
      throw new RuntimeException(e.toString());
    }
  }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OutputS3DTO{
  /**
   * 
   */
  private static final long serialVersionUID = 1L;

  private String id;
  private String name = "S3 storage config";
  private String bucketName;
  private String accessKey;
  private String secretKey;

  public OutputS3DTO(String id) {
    this.id = id;
  }
}

I’m testing with mockite like this:

package br.com.video;

@RunWith(MockitoJUnitRunner.class)
public class EncodingVideoTestApplicationTests {

  @InjectMocks
  private VideoEncodingService videoEncodingService;

  @Mock
  private MainService mainService;


  @Test
  public void createOutputS3() {
    videoEncodingService = new VideoEncodingService(mainService);
    OutputS3DTO s3 = new OutputS3DTO("1");
    Config config = new Config();
    Mockito.when(mainService.returnObject(Mockito.anyString(), Mockito.any(), Mockito.any()))
        .thenReturn(s3);
    videoEncodingService.createOutputS3(config);
    assertEquals(config.getIdOutputS3(), "1");
  }

}

Along those lines:

cf.setIdOutputS3(os3.getId());

os3 is always null

  • Noted the test class with @RunWith(MockitoJUnitRunner.class)? There is another method called returnObject on mainService?

  • @Dherik.. The returnObject method is unique...I updated the post with the full code

1 answer

0

This is Samuel. I believe that your call pro createOutputS3 inside the test, is instantiating the Videoencodingservice class with null values in the properties.

With this, when you use Mockito.anyString(), it will wait for a string to understand that that call should be mocked, but as it is coming null in "urlEndpointOutputS3", the mock does not happen.

Try debugging to see if this is really happening, and if so, change anyString to "any". If any does not accept null, set all your mock parameters to "null" instead of "any"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.