Reputation: 81
Can someone please, tell me how you can write a test. I now have to test sending a request from one server to another using RestTemplate
.
class ServiceTest {
@Mock
private RestTemplate restTemplate = new RestTemplate();
@InjectMocks
private RConsumerService refundConsumerService = new RConsumerService(new RestTemplateBuilder());
@Test
public void sendRequestToBillingService(){
ChargeResponse chargeResponse = new ChargeResponse();
chargeResponse.setInstanceKey("testInstanceKey");
KafkaMessage kafkaMessage = new KafkaMessage();
kafkaMessage.setApplication_id(1L);
kafkaMessage.setCompany_id(1111);
TransactionRequestContext reqContext = refundConsumerService.createTxnRequestContext(kafkaMessage);
Mockito.when(restTemplate.postForEntity(Mockito.any()
, refundConsumerService.buildChargeRequest(reqContext), ChargeResponse.class))
.thenReturn(new ResponseEntity<>(chargeResponse, HttpStatus.OK));
refundConsumerService.refund(kafkaMessage);
assertEquals(chargeResponse.getInstanceKey(), "testInstanceKey");
}
}
How do I write the condition correctly in
Mockito.when(restTemplate.postForEntity(Mockito.any()
, refundConsumerService.buildChargeRequest(reqContext), ChargeResponse.class))
.thenReturn(new ResponseEntity<>(chargeResponse, HttpStatus.OK));
Now I am getting this exception java.lang.IllegalArgumentException: URI is required
Upvotes: 0
Views: 864
Reputation: 2740
As you are using @Mock
and @InjectMocks
, you don't need to create new
instance of those objects. Mockito
will inject it for you. I guess you have this exception because of this parameter : Mockito.any()
in your Mockito.when()
. It have to be of a Uri
type.
Your code will looks like this :
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private RConsumerService refundConsumerService;
@Test
public void sendRequestToBillingService() {
ChargeResponse chargeResponse = new ChargeResponse();
chargeResponse.setInstanceKey("testInstanceKey");
KafkaMessage kafkaMessage = new KafkaMessage();
kafkaMessage.setApplication_id(1L);
kafkaMessage.setCompany_id(1111);
TransactionRequestContext reqContext = refundConsumerService.createTxnRequestContext(kafkaMessage);
URI mockUri = URI.create("http://localhost/mockUri");
Mockito.when(restTemplate.postForEntity(mockUri
, refundConsumerService.buildChargeRequest(reqContext), ChargeResponse.class))
.thenReturn(new ResponseEntity<>(chargeResponse, HttpStatus.OK));
refundConsumerService.refund(kafkaMessage);
assertEquals(chargeResponse.getInstanceKey(), "testInstanceKey");
}
}
Upvotes: 1