Mockito:不在测试函数中抛出错误

Mockito: not throwing error in a test function

我尝试使用 junitmockito 来测试一些功能。

但是由于一些我不知道的原因,我无法成功测试抛出异常。

这是我的代码:

用户服务:

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);
}

用户资料库:

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

用户:

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

这是测试方法:

@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");
    }

}

谁能告诉我为什么测试方法没有抛出任何错误?

您的用户丢失了。 isValidUser() 首先检查 isEnabledUser() 哪个 return 是错误的,因为您的存储库没有 return 用户。所以 isValidSomething() 永远不会执行,也不会抛出任何异常。