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

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

问题描述:

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

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.

以下是受测试的类:

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;
    }
}

我的测试类是:

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

    }
}

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

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.

我知道用这种方法创建Print对象并注入对象是更好的方法,但是我想测试代码,因为打印对象是在方法内创建的。有什么方法可以做到这一点

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

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

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?