测试-如何创建Mock对象 [英] Testing - how to create Mock object

查看:228
本文介绍了测试-如何创建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.

请注意,您选择MyTest作为要测试的类有点不幸,因为名称暗示它本身就是测试本身.我将其更改为MyClass.另外,可以通过传入A的实例来轻松替换在构造函数中创建对象的过程,因此我将创建的内容移至以后将被调用的方法.

Note that your choice of MyTest as the class to be tested is a bit unfortunate as the name implies that it is the test itself. I'll change it to MyClass. Also, creating the object in the constructor could easily be replaced by passing in an instance of A so I'll move the creation to a method that would be called later.

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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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