在C#中模拟一个类中的实例

时间:2013-01-10 16:13:17

标签: c# rhino-mocks

我正在尝试模拟一个类中的实例。这是课程(简化):

public void CreatePhotos(string elementType) 
{ 
    var foo = new PicturesCreation(); 

    //some code here...

    if (elementType == "IO") 
    { 
        foo.CreateIcons(client, new PicturesOfFrogsCreation(), periodFrom, periodTo)
    } 
}

所以我试图模拟这个'新的PicturesOfFrogsCreation()'进行单元测试,看看是否用这个参数调用了CreateIcons。我尝试使用Rhino Mocks / AssertWasCalled方法在我的测试中实现这一点,但它看起来不起作用,因为我只知道如何模拟接口。你知道是否可以嘲笑这个?

更新:PicturesCreation类的代码:

internal sealed class PicturesCreation 
    { 
      public void CreateIcons(IPictures foo, int periodFrom, int periodTo) 

         { 
            foo.CreateIcons(periodFrom, periodTo); 
         } 
    }

和PicturesOfFrogsCreation的代码:

internal sealed class PicturesOfFrogsCreation : IPictures
{ 

    public void CreateIcons(int periodFrom, int periodTo) 
      { 
         //Code that implements the method
      } 
}

我写了这个测试,但我不确定它是否写得很好:

public void Create_commitment_transaction_should_be_called_for_internal_order() 
    { 

       IPicture fooStub = RhinoStubWrapper<IPicture>.CreateStubObject(); 

       rebuildCommitmentsStub.StubMethod(x => x.CreateIcons(Arg<int>.Is.Anything, Arg<int>.Is.Anything));

       PicturesProcess.CreatePhotos("IO"); 

       rebuildCommitmentsStub.AssertWasCalled(x => x.CreateIcons(Arg<int>.Is.Anything,Arg<int>.Is.Anything));

    }

提前致谢!

一个。

3 个答案:

答案 0 :(得分:4)

说实话,您的代码似乎并不是为此而设计的。因为您在方法中实例化实例,然后调用该方法,所以很难将其嘲笑。

如果您将实例传递给此方法,或者传递给要在字段中捕获的类的构造函数,那么它可以替换为模拟 - 大多数模拟框架(包括Rhino)可以执行此操作,前提是方法你检查是虚拟的。


编辑:我从编辑中看到有问题的课程是密封的。这使得它们基本上不可移动。模拟一个类的工作方式是创建一个继承自被模拟类的代理类 - 如果它被密封,则无法完成。

答案 1 :(得分:1)

您需要注入要模拟的依赖项。局部变量对方法是私有的,不能断言。一个例子 -

public class Photo{
  private IPicturesCreation foo;
  public test(IPicturesCreation picturesCreation)
  {
    foo = picturesCreation;
  }

  public void CreatePhotos(string elementType) 
    { 
    //some code here...

    if (elementType == "IO") 
       { 
           foo.CreateIcons(client, new PicturesOfFrogsCreation(), periodFrom, periodTo)
       } 
    }
}

然后像这样测试

public class PhotoTest{
    public testFunctionCall(){
    var mockPicturesCreation = new Mock<IPicturesCreation>();
    new Photo(mockPicturesCreation.Object).CreatePhotos("blah");
    mockPicturesCreation.Verify(x => x.CreateIcons(.....), Times.Once);
    }
}

答案 2 :(得分:0)

正如其他人已经提到的,这段代码不适合模拟。 但是,如果您无法修改代码,则仍有一些选项。

我听说TypeMock可以模拟密封的课程,但我从未使用它。这是商业软件btw ... 还有Microsoft Fakes Framework(附带VS Premium)。我玩了一下,看起来你几乎可以测试一下。绝对值得一试!

相关问题