Reputation: 983
I am trying to stub a response that is coming back from a web server to my application, in order to be able to carry out component tests on my application. I have a RestTemplate XML that I would like my requestFactory to consume to create responses based on the XML. Example of the XML is below.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rates-file xmlns="http://www.example.com/schema/rates-file">
<timestamp>2017-06-30T14:20:21.768+10:00</timestamp>
<daily-rates-updated>true</daily-rates-updated>
<number-of-records>96</number-of-records>
<rate>
<transaction-type>transaction</transaction-type>
<product-code>product</product-code>
<code>code</code>
<description>description</description>
<rate>2.6154</rate>
</rate>
<number-of-records>96</number-of-records>
<rate>
<transaction-type>transaction2</transaction-type>
<product-code>product2</product-code>
<code>code2</code>
<description>description2</description>
<rate>2.6154</rate>
</rate>
...
For this purpose I am using MockClientHttpRequest and MockClientHttpResponse (part of spring-test). How do I have the MockClientHttpRequest consume this XML and consequently produce my responses?
EDIT: Just to clarify this is the part of code I am trying to direct to my XML:
public RatesFile fetchRatesFile() {
...
try {
...
**ratesFile = restTemplate.postForObject(exampleUrl, variables, RatesFile.class);**
...
}
return ratesFile;
}
Instead of overriding postForObject method, I would like to write a RequestFactory that responds to the HttpMethod.POST request by using the XML.
Upvotes: 1
Views: 488
Reputation: 24593
I'd not mess with the RestTemplate
, simply due to the fact that I'd not be testing the Prod code in that case. What I'd do is override exampleUrl
in my test, and then stand up an endpoint that responds to that. Here's how:
properties
attribute on @SpringBootTest
to set exampleUrl=http://localhost:8080/test
. Also throw in @DirtiesContext
in that case. Otherwise, create an application.properties
in the src/test/resources
directory and put the property in that.@RestController
in the test package that has a method mapped to /test
, ORUsing either #2 or #3, you receive the HTTP request and can return whatever response you want to based on that.
Upvotes: 2