本文介绍了测试-如何创建Mock对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何创建Mock对象来测试如下代码:

I am just wondering how can I create Mock object to test code like:

public class MyTest
{
  private A a;
  public MyTest()
  {
     a=new A(100,101);
  }
}

?

谢谢

推荐答案

直接使用new实例化对象的代码使测试变得困难.通过使用工厂模式,您可以将对象的创建移到要测试的代码之外.这为您提供了一个放置模拟对象和/或模拟工厂的地方.

Code that instantiates objects using new directly makes testing difficult. By using the Factory pattern you move the creation of the object outside of the code to be tested. This gives you a place to inject a mock object and/or mock factory.

public interface AFactory
{
    public A create(int x, int y);
}

public class MyClass
{
    private final AFactory aFactory;

    public MyClass(AFactory aFactory) {
        this.aFactory = aFactory;
    }

    public void doSomething() {
        A a = aFactory.create(100, 101);
        // do something with the A ...
    }
}

现在,您可以在测试中传递一个模拟工厂,该工厂将创建您选择的模拟AA.让我们使用Mockito创建模拟工厂.

Now you can pass in a mock factory in the test that will create a mock A or an A of your choosing. Let's use Mockito to create the mock factory.

public class MyClassTest
{
    @Test
    public void doSomething() {
        A a = mock(A.class);
        // set expectations for A ...
        AFactory aFactory = mock(AFactory.class);
        when(aFactory.create(100, 101)).thenReturn(a);
        MyClass fixture = new MyClass(aFactory);
        fixture.doSomething();
        // make assertions ...
    }
}

这篇关于测试-如何创建Mock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:39