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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…