当前位置: 首页 > 面试题库 >

模拟对象内部测试方法

史昀
2023-03-14
问题内容

我有一个要测试的类。只要有可能,我都会对该类进行依赖注入,该注入依赖于其他类的对象。但是,我遇到了一种情况,我想在不重新构造代码的情况下模拟对象,而不是应用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类中对其进行了模拟,但是它是在被测试的方法中创建的。我做了研究,但找不到任何好处。资源。

我知道从该方法中创建Print对象是最好的方法,但我想对代码进行测试,方法是在方法内部创建Print对象。有没有办法做到这一点?


问题答案:

如果您只想模拟car.printDelegate()的返回值,那么如何模拟该调用的任何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?


 类似资料:
  • 遇到了另一个常见的问题,同时为Spring Batch编写单元测试和集成测试组件是如何模拟域对象。一个很好的例子是StepExecutionListener,如下所示: public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport { public ExitStatus afterSte

  • redis-cli -p 6379 DEBUG sleep 30

  • redis-cli debug oom redis直接退出。

  • 我有以下两门课 我想对SampleTest getResult()进行单元测试,但我想在这里模拟Test1(),这样我就可以返回我在UnitTests中设置的任何值。这些课我都改不了。 我使用Mockito尝试了一些模式,但没有成功。 请提出一些好的建议。

  • 我有一些遗留代码,并对我在该代码上所做的增强进行了编写测试。我有一个类SiteSession,并提取了一个接口ISiteSession,以便将依赖项注入到调用类中。 调用类有一个构造函数,在该构造函数中,依赖项被注入到正在测试的控制器CustomerDetails中 现在,我的测试方法已经嘲弄了依赖关系,并且我对为这个控制器或代码的任何其他部分创建的任何测试都没有问题。但是,当调用该控制器上的测试

  • 所以我想做一些事情 但我得到了空异常