比较 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/