Jakov
Jakov

Reputation: 989

Mockito: not throwing error in a test function

I tried to test some functionalities by using junit and mockito.

But due to some reasons unknown to me, I cannot successfully test throwing of an exception.

This is my code:

UserService:

public class UserService {
   private final UserRepository userRepository;
   private final CheckSomething checkComething;

   public UserService(UserRepository userRepository, CheckSomething checkComething) {
       this.userRepository = userRepository;
       this.checkSomething = checkSomething;
   }

   public boolean isValidUser(String id, String something) {
        User user = userRepository.findById(id);
        return isEnabledUser(user) && isValidSomething(user, something);
   }

   private boolean isEnabledUser(User user) {
        return user != null && user.isEnabled();
   }

   private boolean isValidSomething(User user, String something) {
       String checkedSomething = checkSomething.check(something);
       return checkedSomething.equals(user.getSomething());
   }
}

CheckSomething:

public interface CheckSomething{
    String check(String something);
}

UserRepository:

public interface UserRepository {
    User findById(String id);
}

User:

@Getter
@Setter
@AllArgsConstructor
public class User {
    private String id;
    private String something;
    private boolean enabled;
}

This is the testing method:

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

    @InjectMocks
    private UserService userService;

    @Mock
    private UserRepository userRepository;

    @Mock
    private CheckSomething checkSomething;

    @Test(expected = IllegalArgumentException.class)
    public void testThrowingRandomException() {
        Mockito.when(checkSomething .check(Mockito.anyString())).thenThrow(new IllegalArgumentException());

        userService.isValidUser("1", "1");
    }

}

Can someone tell me why is the testing method not throwing any error?

Upvotes: 1

Views: 50

Answers (1)

Milgo
Milgo

Reputation: 2767

Your user is missing. isValidUser() checks isEnabledUser() first which returns false because your repository does not return an user. So isValidSomething() is never executed and can't throw any exception.

Upvotes: 1

Related Questions