Reputation:
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?
Upvotes: 21
Views: 71178
Reputation: 2386
You can start a test-http-server in your unit-test. There are several frameworks to do it. For example Mockserver and Wiremock.
Upvotes: 6
Reputation: 2048
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.
Upvotes: 3
Reputation: 970
HttpResponse httpResponse = mock(HttpResponse.class);
see this: Mocking Apache HTTPClient using Mockito
Upvotes: 9