Traxex1909
Traxex1909

Reputation: 2710

Using mocked objects

I've just started unit testing on Android with Mockito - how do you get the class that you are testing on to use the mocked class/object instead of the regular class/object?

Upvotes: 0

Views: 62

Answers (2)

Saurabh
Saurabh

Reputation: 2472

  1. You can use @InjectMocks for the class you writing the test.

    @InjectMocks private EmployManager manager;

  2. Then you can use @Mock for the class you are mocking. This will be the dependency class.

    @Mock private EmployService service;

  3. Then write a setup method to make things available for your tests.

@Before
public void setup() throws Exception {
  manager = new EmployManager();
  service = mock(EmployService.class);
  manager.setEmployService(service);
  MockitoAnnotations.initMocks(this);
}

Then write your test.

@Test
public void testSaveEmploy() throws Exception {
    Employ employ = new Employ("u1");
    manager.saveEmploy(employ);

    // Verify if saveEmploy was invoked on service with given 'Employ'
    // object.
    verify(service).saveEmploy(employ);

    // Verify with Argument Matcher
    verify(service).saveEmploy(Mockito.any(Employ.class));
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

By injecting the dependency:

public class ClassUnderTest
    private Dependency dependency;

    public ClassUnderTest(Dependency dependency) {
        this.dependency = dependency;
    }

    // ...
}

...

 Dependency mockDependency = mock(Dependency.class);
 ClassUnderTest c = new ClassUnderTest(mockDependency);

You can also use a setter to inject the dependency, or even inject private fields directly using the @Mock and @InjectMocks annotations (read the javadoc for a detailed explanation of how they work).

Upvotes: 0

Related Questions