在测试中的方法内部创建的模拟对象 [英] Mocking Objects Created Inside method Under test

查看:22
本文介绍了在测试中的方法内部创建的模拟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想测试的类.只要有可能,我就会对依赖于其他类对象的类进行依赖注入.但是,我遇到了一个案例,我想在不重组对象的情况下模拟对象代码而不是应用 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.

我知道从这个方法中创建打印对象并注入对象是更好的方法,但我想测试代码原样,在方法内部创建打印对象.有什么办法吗这个

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

推荐答案

如果你只是想mock car.printDelegate() 的返回值,那么mock 任何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?

这篇关于在测试中的方法内部创建的模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆