模拟对象创建内部方法测试中

我有一个我想测试的类。只要有可能,我会依赖于其他类的对象对该类进行dependency injection。但是,我遇到了一个案例,我想在没有重构代码的情况下模拟对象而不是申请DI。

这是被测试的课程:

public class Dealer { public int show(CarListClass car){ Print print=new Print(); List list=new LinkedList(); 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; } } 

我的测试类是:

 public class Tester { Dealer dealer; CarListClass car=mock(CarListClass.class); List carTest; Print print=mock(Print.class); @Before public void setUp() throws Exception { dealer=new Dealer(); carTest=new LinkedList(); 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 } } 

我无法弄清楚在Dealer类中模拟打印对象的解决方案。因为,我在Test类中模拟它,但它在测试中的方法中创建。我做了我的研究,但找不到任何好处资源。

我知道从这个方法中创建Print对象并注入对象是更好的方法,但是我想按原样测试代码,在方法中创建print对象。有什么方法可以做到这一点

如果你只想模拟car.printDelegate()的返回值,那么如何模拟调用的任何Print实例?

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

顺便说一句,我对你的下列代码感到困惑: –

 List list=new LinkedList(); // allocate a empty list worth list=car.getList(); // nothing but wasting memory. ... return num; // no definition, do you mean printedLines?