在测试方法中创建的模拟对象

7

我有一个类需要进行测试。在可能的情况下,我会对这个依赖其他类对象的类进行依赖注入。但是,有时候我想模拟对象,而不重构代码或应用 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类中的打印对象。因为我是在测试类中进行模拟,但它是在被测试的方法中创建的。我做了研究,但没有找到任何好的资源。

我知道将Print对象的创建移出该方法并注入该对象是更好的方式,但我想按照现有代码测试,即在方法内部创建打印对象。是否有任何方法可以实现这一点?


当汽车模拟对象遇到预期的getList()方法时,它会返回我在测试用例中添加的列表,但是在到达printDelegate()方法时,它总是返回零,尽管我指定了9作为返回值。我认为这是因为Print对象是在被测试的方法中创建的。 - user3897395
1
我找到了一个解决方案,可以在这篇文章中克服这个问题。希望这也能帮助其他人。 https://code.google.com/p/mockito/wiki/MockingObjectCreation - user3897395
PowerMock和JMockit允许模拟构造函数调用,但是当可行时,您找到的帖子提供了更好的解决方案。 - John B
1个回答

6
如果您只是想模拟car.printDelegate()的返回值,那么如何为调用mock任何Print实例?
when(car.printDelegate(org.mockito.Matchers.any(Print.class))).thenReturn(9);

顺便说一下,我对你的以下代码感到困惑:-
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...我使用了org.mockito.Matchers.any(Print.class),它很好地解决了我的问题。 - user3897395
Matchers.any在新版本中已被弃用,使用ArgumentMatchers.any将会抛出空指针异常。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接