简体   繁体   中英

Spring Boot tests for remote server

I'm using jUnit and SpringBootTest for my application. eg:

mvc.perform(MockMvcRequestBuilders.get("/categories")...

Is that possible to run tests on a remote server? eg

mvc.perform(MockMvcRequestBuilders.get("192.168.1.1:80/categories")... 

I don't think it's possible, as it's beyond a unit test or an integration test. If you're testing an existing webservice, it's not a mock anymore. For getting data from an external webservice, you can use the RestTemplate class:

public class Application {

private static final Logger log = LoggerFactory.getLogger(Application.class);

public static void main(String args[]) {
    RestTemplate restTemplate = new RestTemplate();
    Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
    log.info(quote.toString());
}}

(Example taken from Spring docs )

Spring MVC Test Framework is meant to test Spring MVC controllers without actually starting up HTTP server.

In your case, in your JUnit tests you should use real HTTP client (like RestTemplate ) or to keep things even simpler go with Rest Assured library that was designed for that.

Sample Rest Assured based test:

given().
    param("key1", "value1").
    param("key2", "value2").
when().
    post("/somewhere").
then().
    body(containsString("OK"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM