简体   繁体   中英

run Java Servlet unit tests on Tomcat server

I have a Java HttpServlet. When we send a get Request to this servlet, it checks whether a file in the server exist or not. if not create a new file.

I want to write some unit tests. When a get request sends, assert that the new file created. My problem is my tests running on my local machine, not the Tomcat Server and temp files created in the local server.

here is my code:

    HttpGet httpGet = new HttpGet("localhost:8080/myfilename");
    HttpClient httpClient = HttpClientBuilder.create().build();
    httpClient.execute(httpGet);

    File directory = new File("myfilename");

    // then
    assertTrue(directory.exists());

how to run the unit tests, on the tomcat server?

Distinct non-answer: you don't do that.

Long answer: unit tests are about testing units in isolation . And in order to be useful, you mock/stub anything external, such as: a web or application server.

In other words: a real unit test should be written for the code that your server invokes for a specific URL. You could write a decent unit test that ensures: "when I am called, I check for that file, if not, create it".

Then you test that, independent of any Tomcat server.

Then, later on, you might want to test that your end to end feature works. But of course, then you should only be using APIs that your server itself has to offer.

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