-2

I am running a very basic unit test using Mockito

As a part of that test I have these lines

@Mock 
RestTemplate restTemplate;
...

@Before
target = new ServiceClass(params);
ReflectionTestUtils.setField(target, "url", "http://dummyendpoint");
...

@Test
byte[] expectedResponse = "any old byte array".getBytes();
given( restTemplate.postForObject( any (String.class), any( HttpEntity.class ), eq( byte[].class ), eq( param1 ), eq( param2 ), eq( param3 ) ) ).willReturn( expectedResponse );

byte[] response = target.performAction( creds, param1, param2, param3);

I realise this is a bit vacuous but a) it serves my purpose for now and b) I may build on it

So in the Service I have a method under test

@ResponseBody public byte[] performAction( SessionAuthenticationCredentials creds, String param1, String param2, String param3 ) {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders httpHeaders = getHttpHeaders( SessionAuthenticationCredentials );
    HttpEntity<Object> entity = new HttpEntity<Object>( httpHeaders );
    return restTemplate.postForObject( buildURL(), entity, byte[].class, param1, param2, param3 );
}

private String buildURL() {
    return url;
}

What I am finding is that I am getting errors when it calls postObject method in the performAction method. I believe this is because my stub is not being invoked as all the errors I get are a result of the post trying to actually use the url (if it is a valid url then "I/O error on POST request for...", if it's nonsense then "java.lang.IllegalArgumentException: URI is not absolute".

Can anyone point why my stub is ignored ? Maybe I'm misunderstanding the use of any () ?

gringogordo
  • 1,990
  • 6
  • 24
  • 60
  • 2
    Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the source code you have as a [mcve], which can be compiled and tested by others. – Progman Jun 06 '20 at 15:37

1 Answers1

1

In your test you are creating a mock of RestTemplate and set some expectations on it, but in your service you are cerating a new instance of RestTemplate. Thus, any expectations you set in the test are ignored.

To solve:

  • use a RestTemplate field in the service. It is safe. See Is RestTemplate thread safe?
  • Provide a way for set it in. Constructor param in the service looks appropriate
  • Set the field to a mock in your test.
Lesiak
  • 22,088
  • 2
  • 41
  • 65