Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking void method with EasyMock and Mockito

Hello I would like to know what is the best approach to mock void methods for example: I have a PersonManager under the test and then I have dao that is mocked.

class PersonManager {

    PersonDao dao...

    PersonManager(PersonDao dao)...

    Preson find(String person)...

    void delete(String person)...

}

class PersonManagerTest {

    Map<String, Person> persons ..... = "person1", "person2", "person3";

    PersonDao mock...

    PersonManager manager = new PersonManager(mock);

    //easy one
    @Test public void shouldReturnExistingPerson() {
        expect(mock.find("person1").andReturn(persons.get(0));
        Person result = manager.find("person1");
        // replay and verify logic
    }

    //but what should I do here?
    @Test public void shouldDeleteExistingPerson() {
        //should I remove a person from testing Map holding test data? or what am I doing wrong
    }
}

So testing method with return was easy but how to toset void method? Thank you for suggestions, and Mcokito examples are welcomed too. }

like image 487
Jarek Avatar asked Dec 21 '22 14:12

Jarek


2 Answers

With easy mock, you don't need to wrap void functions around expect(). You just need to do something like:

obj = createMock(...)
obj.someVoidMethod();
replay(obj);
...
verify(obj);
like image 97
Amir Raminfar Avatar answered Jan 05 '23 11:01

Amir Raminfar


It depends entirely on what you're trying to test.

In mockito, if you want to check only that the DAO delete method is called with the correct parameter, then verify is what you want.

I would suggest that this is exactly what you want since your unit test for PersonManager should not be testing PersonDao.

like image 36
Alan Escreet Avatar answered Jan 05 '23 09:01

Alan Escreet