JUnit Mockito always returns false in assertEquals when comparing boolean values.
@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);
}
}
This method always return false even if the username is blocked. Why is it behaving like this?
There's no JUnit assertEquals with 2 booleans so you need to use different method - assertTrue :
Asserts that a condition is true. If it isn't it throws an AssertionError without a message.
assertTrue(accountBlocked);
But in your case your class is mocked and therefore by default all its method with Boolean return value will return 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.
So unless you mock the method behavior using when
you can assertFalse it
assertFalse(accountBlocked);
You aren't mocking any behavior. By default, calling a boolean method on a mock returns false.
To mock the behavior you are looking for:
Mockito.when(userService.isAccountBlocked("username")).thenReturn(true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.