I'm a newbie to Java Unit test. The issue I'm facing is that I need to develop a JUnit test to send requests to a server'API to test two methods: addUser
and deleteUser
. If I want to add/delete a user from the server, I need to get an authentication token from the server; However, due to some issue on the server side, I currently can't get a valid token. So what comes to my mind, is to mock the server's behavior that if the server receives requests from the Unit test, it could response with a JSON data which indicates the status of the add/delete-user operations.
Because I'm totally new to JUnit. I have no clue how to implement the operation. So my question is what is probably the easiest way to apply the mock?
HttpResponse httpResponse = mock(HttpResponse.class);
You can start a test-http-server in your unit-test. There are several frameworks to do it. For example Mockserver and Wiremock .
You can do it by using the HTTP Unit Testing from Google .
In order to generate a simple HTTP response you can use this code :
HttpTransport transport = new MockHttpTransport();
HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
You can also customize your testing by overriding the implementation of the MockHttpTransport class.
You can check here the repo of this for more details. I think it can be suitable for you.
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.