Reputation: 21
I have a doubt with Mockito. I would want to test this simple class:
public class MyClass{
private UserService userService;
public void deleteUser(){
userService.getAdminUser(1);
userService.deleteUser(0);
}
}
I wrote this simple test:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@MockitoAnnotations.Mock
private UserService userService;
@Test
public void test(){
MyClass myClass=new MyClass();
myClass.userService=userService;
myClass.deleteUser();
}
}
This test run with no errors. I await that it didn't compile because there isn't any call to userService method..
Upvotes: 2
Views: 317
Reputation: 121712
Here is how you would test it with a different set of methods which invokes no annotations. Note that this is TestNG, but adapting it to JUnit 4+ is easy:
import static org.mockito.Mockito.*;
public final class Test
{
private UserService userService;
@BeforeMethod
public void init()
{
userService = mock(UserService.class);
}
@Test
{
final MyClass myClass = new MyClass();
myClass.userService = userService;
myClass.deleteUser();
verify(userService, times(1)).getAdminUser(1);
verify(userService, times(1)).deleteUser(0);
}
}
Note that there is a one-argument only verify()
variant, which is exactly equivalent to having times(1)
as the second argument. There is also never()
.
If for instance you wanted to test that the .deleteUser()
method was not called with any argument, you'd do:
verify(userService, never()).deleteUser(anyInt());
Upvotes: 0
Reputation: 691645
Mocks created by Mockito are "smart". They don't do anything when a void method is called. They return null when a method returning an object is called. They return an empty collection when a method returning a collection is called.
If you want to verify that getAdminUser()
and deleteUser()
have been called, use Mockito.verify()
.
These two things are explained in the Mockito documentation, points 1 and 2. In particular:
By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).
Upvotes: 3
Reputation: 1922
you have not added any check to see if userService is used in any way. Adding a verify will do that for you: When to use Mockito.verify()?
I would advice you to read up on how Mockito works in tests, I think you have jumped past some of the fundamentals when it comes to learning the design and how method calls to the mock is treated.
Upvotes: 0