Thai Tran
Thai Tran

Reputation: 9935

Correct way to make a mock test

In my code base, I have a function like this

ABCDAO abcDao; 

public A(ABCDAO abcDao) {
   this.abcDao = abcDao;
}

public ABC listABCElement(String arg, boolean withError) {
  return abcDao.getABC(arg, withError);
}

Since the DAO are connected to a web service (with many configurations, hard to setup and it definitely will take some time to test, since it will connect to the real server...) and take back the result, I decided to use mock test (PowerMockito + Mockito) to test the listABCElement function. However, let 's say when doing the mock test, I will use

ABCDDAO abcDao = Mockito.mock(ABCDAO.class);
Mockito.when(abcDao.getABC("", true)).thenReturn(new ABC());
......
assertNotNull(obj.listABCElement("", true));

I dont feel it make any sense, since I am forcing the result of function to return something and then test if it does return anything (!?!?!)

What is the correct way to do the unit test in this scenario?

Upvotes: 1

Views: 170

Answers (1)

Mureinik
Mureinik

Reputation: 311808

Your notion is correct - such a test is meaningless. Effectively, you're testing that Mockito works as advertised.

What you'd probably want to do in such a scenario is a flow test. Your class A doesn't really have any logic of its own, it just delegated to ABCDAO - so that's exactly what you'd want to test. The way to do this is to mock ABCDAO (although defining behavior for this call is redundant), but instead of asserting the value (which, as you noted is pointless), you'd use Mockito to verify that the correct method was called:

@Test
public void testListABC() {
    // Mock the ABCDAO
    ABCDAO abcDao = Mockito.mock(ABCDAO.class);

    // Create an A instance using it
    A a = new A(abcDao);

    // Call a's method
    a.listABCElement("",true);

    // Verify the correct method of abcDao was called 
    Mockito.verify(abcDao).getABC("", true);

    // Verify no other methods were called on abcDao
    Mockito.verifyNoMoreInteractions(abcDao);
}

Upvotes: 1

Related Questions