-1

Below is my code and I am writting Junit test case for method perform. I want method getList to return dummy values as DB is not available. Please suggest how I can do the same using JMockit.

class BaseClass {

  public List<> getList() {
      return DataBase.getList();       
  }
}

class ChildClass extends BaseClass {

  public boolean perform(String temp) {
     boolean bool=true;
     List list = getList();
     for(String str:list){
           if(str.equals(temp);
               bool=false;
           break;
     }
     return bool;
  }
}
Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28
user1520277
  • 59
  • 2
  • 11
  • I am not longer using JMockit and switched to Mockito. Using @Mock annotation above issue can be resolved. – user1520277 Aug 16 '16 at 19:57
  • You mean the `@Spy` annotation, probably. But the JMockit test is simpler anyway. – Rogério Aug 16 '16 at 20:37
  • 1
    @user1520277 -- If you don't care for your question any longer, and you don't mark any of the answers as helpful, could you delete it rather than leave it unanswered? – Markus Mitterauer Aug 17 '16 at 15:09

2 Answers2

1

It's not BaseClass#getList() that should be mocked, but DataBase#getList():

public class ExampleTest {
    @Tested ChildClass cut;

    @Test
    public void findItemInList(@Mocked DataBase db) {
        List<String> list = Arrays.asList("Abc", "test", "def");
        new Expectations() {{ DataBase.getList(); result = list; }};

        boolean itemNotFound = cut.perform("test");

        assertFalse(itemNotFound);
    }
}

Mocking BaseClass#getList() would require partial mocking, which can be done with new Expectations(cut) {{ cut.getList(); result = list; }}. But partial mocking is a known bad testing practice that should be avoided.

Rogério
  • 16,171
  • 2
  • 50
  • 63
0

As long as ChildClass does not overwrite BaseClass::getList() you have to mock BaseClass::getList():

new MockUp<BaseClass>() {
    @Mock
    List<> getList() {
        return new ArrayList(); // your mock here
    }
 }
Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28