Search code examples
javaunit-testinggenericsjunitjmockit

Java Mockit : How to Mock a generic class method in JMockit


Hi I have the following classes

public class DataAccessLayer<T> {
  public T getData(Class<?> dataInfoType ,Integer id){
  //Some logic here
  } 
}

public class ServiceLayer{
    //this method has to be tested
     public Integer testingMethode{
         //The following line should be mocked
         UtilClass info =  new DataAccessLayer<UtilClass>().getData(UtilClass.class, 1); 
        retutn info.getSomeFieldWithIntegerValue();
     }
 }

I want to write test cases for testingMethode for that I need to mock the getData() method in DataAccessLayer<T>

Is it possible with jmockit to mock a Template(Generic ) class?


Solution

  • A generic class can be mocked the same way a non-generic one:

    @Test
    public void example(@Mocked final DataAccessLayer<UtilClass> mock)
    {
        final UtilClass data = new UtilClass(123);
        new Expectations() {{ mock.getData(UtilClass.class, 1); result = data; }};
    
        int result = new ServiceLayer().testingMethode();
    
        assertEquals(123, result);
    }