java - 比较 boolean 值时,JUnit Mockito 在assertEquals 中始终返回 false

标签 java junit mockito assert

比较 boolean 值时,JUnit Mockito 总是在assertEquals 中返回 false。

 @RunWith(MockitoJUnitRunner.class)
 public class UserServiceTest { 
    @Mock
    private UserService userService;

    @Mock
    private UserRepository userRepository;

    @Test
    public void testIsAccountBlocked() {
        Boolean accountBlocked = userService.isAccountBlocked("username");
        assertEquals(true, accountBlocked);
    }   
}

即使用户名被阻止,此方法也始终返回 false。为什么会这样?

最佳答案

没有 JUnit assertEquals有 2 个 boolean 值,因此您需要使用不同的方法 - assertTrue :

Asserts that a condition is true. If it isn't it throws an AssertionError without a message.

assertTrue(accountBlocked);

但是在您的情况下,您的类被模拟,因此默认情况下其所有具有 boolean 返回值的方法都将返回 false

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

因此,除非您使用 when 模拟方法行为,否则您可以断言它

assertFalse(accountBlocked);

关于java - 比较 boolean 值时,JUnit Mockito 在assertEquals 中始终返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620406/

相关文章:

java - 使用 Java 从格式化字符串中提取

java - Mockito 当方法仅在调试时工作

模拟集成测试

java - 如何使用 try-with-resources 测试方法

java - JSON Jackson 将不同的键解析到同一个字段中

java - 无法使用 Selenium WebDriver 将 Keys() 发送到 TinyMCE

java - 调用私有(private)静态 void 方法

java - Junit 4 ExpectedException.expectMessage 应该无法通过测试,但事实并非如此

java - 安卓工作室 : Unlock Screen Orientation On Button Click

junit - JUnit 测试的层次结构