【问题标题】:Mockito: not throwing error in a test functionMockito:不在测试函数中抛出错误
【发布时间】:2020-12-02 13:12:39
【问题描述】:

我尝试使用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");
    }

}

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

【问题讨论】:

  • 请添加您的完整测试类,或者至少添加您如何模拟passwordEncoder 以及您如何创建userService
  • 我添加了,谢谢你的建议。

标签: java exception mocking mockito


【解决方案1】:

您的用户丢失了。 isValidUser() 首先检查 isEnabledUser(),它返回 false,因为您的存储库不返回用户。所以isValidSomething() 永远不会被执行,也不会抛出任何异常。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2012-08-23
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多