vendredi 10 mai 2019

Mocking a function with Mockito throws different error than defined

I have several tests with a mocked service which call the same function and in each test should throw a different error to simulate a different problem. I don't understand why one test works just fine and the exception is thrown, but in an identical test a NullPointerException is thrown.

class UserMutationTest {
    private UserService mockUserService;
    private UserMutation userMutation;

    @BeforeEach
    void setup() {
        mockUserService = Mockito.mock(UserService.class);
        userMutation = new UserMutation(mockUserService);
    }

    //This test works perfectly fine, DataAccessresourceFailureException is thrown and caugh
    //and then a BaseGraphQLException is thrown which is exactly what's expected
    @Test
    void loginDatabaseUnavailable(){
        when(mockUserService.login(anyString(), anyString())).thenThrow(DataAccessResourceFailureException.class);
        assertThrows(BaseGraphQLException.class, () -> userMutation.login(anyString(), anyString()));
    }

    //This test which is a copy/paste of the above test except for instead it's supposed
    //to throw InvalidInputException, but when called it actually throws NullPointerException.
    @Test
    void loginInvalidCredentials(){
        when(mockUserService.login(anyString(), anyString())).thenThrow(InvalidInputException.class);
        assertThrows(InvalidInputException.class, () -> userMutation.login(anyString(), anyString()));
    }
}

public class UserMutation implements GraphQLMutationResolver {
    private final UserService userService;

    @Autowired
    public UserMutation(UserService userService) {
        this.userService = userService;
    }

    public User login(String username, String password){
        try {
            User u = userService.login(username, password);
            return u;
        } catch (DataAccessResourceFailureException e) {
            //Database Unavailable
            log.debug(e.toString());
            BaseGraphQLException ex = new BaseGraphQLException("Database Unavailable");
            ex.addExtension("Database", "Unavailable");
            throw ex;
        } catch (InvalidInputException e) {
            throw e;
        }
        //If I add a catch for NullPointException here it is actually caught, which makes no sense to me.
    }
}

I don't understand why one test would throw the correct defined exception, but another would throw a NullPointerException. If they both threw NullPointer then I would have somewhere else to look, but they don't. Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire