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

编程入门 行业动态 更新时间:2024-10-25 06:20:20
本文介绍了模拟对象创建内部方法测试中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-10-31 04:05:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   方法   测试中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!