How to test if my application method handles HTTP status 404 of a REST API without actually calling that REST API

Viewed 258

I am currently trying to automate some of the testing for my application using JUnit. My application has a method which calls a 3rd party REST API. I need to check if that method is handling HTTP status codes like 404 without actually calling the 4rd party API.

e.g., My Method:

public int getNumUsers(){
    //call the 3rd party API - https://example.com/api/users/count
    //return user count
}

I need to test if the method getNumUsers is handling HTTP status code 404 which could be returned by the 3rd party API - https://example.com/api/users/count.

Any suggestions?

1 Answers

Extract the the http call to the "3rd party API" into its own object. Pass that object into the constructor of the class you want to test.

Now you can replace this in your unit test with a test double (stub/mock) and control what it returns. A proper result value or an error.

Something like this:

this is the 3rd part API

interface UserApi {
    int getUserCount ();
}

your user service will call this api

class UserService {
    private final UserApi api;

    UserService(UserApi api) {
        this.api = api;
    }

    int getUserCount() {
        // todo handle errors
        return api.getUserCount ();
    }
}

and some tests

public class UserServiceTest {

    @Test
    public void shouldProvideUserCount() {

        UserService service = new UserService (new UserApi () {
            @Override
            public int getUserCount () {
                return 1;
            }
        });

        // when
        int count = service.getUserCount ();

        // then
        assertEquals(1, count);
    }

    @Test(expected = UserOperationFailedException.class)
    public void shouldHandleApiError() {
        UserService service = new UserService (new UserApi () {
            @Override
            public int getUserCount () {
                throw new ApiException();
            }
        });

        // when
        service.getUserCount ();
    }

}

You can use a library like Mockito to create the stub instead of implementing it yourself.

Related