7

I have a class which I would like to test.Whenever possible I would do dependency injections for that class which depends on object of other classes.But,I ran into a case where I would like to mock the object without restructuring the code and not appling DI.

Here is the class under test:

public class Dealer {

    public int show(CarListClass car){
        Print print=new Print();

        List<String> list=new LinkedList<String>();

        list=car.getList();
        System.out.println("Size of car list :"+list.size());

        int printedLines=car.printDelegate(print);
        System.out.println("Num of lines printed"+printedLines);

        return num;
    }
}

and my test class for this is:

public class Tester {
    Dealer dealer;

     CarListClass car=mock(CarListClass.class);  
     List<String> carTest;
     Print print=mock(Print.class);

    @Before
    public void setUp() throws Exception {
        dealer=new Dealer();
        carTest=new LinkedList<String>();
        carTest.add("FORD-Mustang");
        when(car.getList()).thenReturn(carTest);
        when(car.printDelegate(print)).thenReturn(9);
    }

    @Test
    public void test() {

        int no=dealer.show(car);
        assertEquals(2,number);//not worried about assert as of now

    }
}

I couldn't figure out a solution to mock the print object inside the Dealer class.Since,I mock it in the Test class,but it gets created in the method under test.I did my research,but couldn't find any good resource.

I know taking Print object creation out of this method and Injection the object is the better way,but I would like to test the code as it is ,with the print object being created inside the method.Is there any way to do this

Kara
  • 6,115
  • 16
  • 50
  • 57
user3897395
  • 103
  • 1
  • 1
  • 9
  • When the car mock object encounters the getList() method as expected it the list I added in the test case,but on reaching printDelegate() method,it always comes as zero,though when I specified as 9 to be the return value.I think this is because the Print object is being created in the method under test. – user3897395 Jul 31 '14 at 21:53
  • 1
    I found a solution to overcome this for this article.I hope this helps other as well https://code.google.com/p/mockito/wiki/MockingObjectCreation – user3897395 Aug 01 '14 at 00:12
  • PowerMock and JMockit allow for mocking constructor calls but the post you found provides a better solution when feasible. – John B Aug 01 '14 at 12:20

1 Answers1

6

If you just want to mock the return value of car.printDelegate(), how about mock any Print instance for the call?

when(car.printDelegate(org.mockito.Matchers.any(Print.class))).thenReturn(9);

By the way, I'm confusing about your following code:-

List<String> list=new LinkedList<String>(); // allocate a empty list worth 
list=car.getList();                         // nothing but wasting memory.
...
return num; // no definition, do you mean printedLines?
Tatera
  • 448
  • 3
  • 11