假设您已对Moq已经有所了解,我们经常会遇到多个Interface,在这个情况下我们如何去Mock它们呢,看下面的示例:
定义下如下的Interface:

   1:      public interface IFirstInterface
   2:      {
   3:         int SomeMethodOnFirstInterface();
   4:      }
   5:   
   6:      public interface ISecondInterface
   7:      {
   8:          int SomeMethodOnSecondInterface();
   9:       
  10:      }
  11:   
  12:      public interface SomeClassImplementingInterfaces : IFirstInterface, ISecondInterface
  13:      {
  14:   
  15:      }

然后定义一个Generic方法实现两个Interface 特别的方法相加,返回结果:

 
   1:      public class SomeClass
   2:      {
   3:          public static int MultipleInterfaceUser<T>(T x)
   4:              where T : IFirstInterface, ISecondInterface
   5:          {
   6:              IFirstInterface f = (IFirstInterface)x;
   7:              ISecondInterface s = (ISecondInterface)x;
   8:   
   9:              return f.SomeMethodOnFirstInterface() + s.SomeMethodOnSecondInterface();
  10:          }
  11:      }

 

让我们来看如何Mock它们:

   1:          [Test]
   2:          public void MultipleInterfaceTest()
   3:          {
   4:              Mock<SomeClassImplementingInterfaces> c =
   5:                  new Mock<SomeClassImplementingInterfaces>();
   6:   
   7:              Mock<IFirstInterface> firstMock = c.As<IFirstInterface>();
   8:              firstMock.Setup(m => m.SomeMethodOnFirstInterface())
   9:                  .Returns(2);
  10:   
  11:              Mock<ISecondInterface> secondMock = firstMock.As<ISecondInterface>();
  12:              secondMock.Setup(m => m.SomeMethodOnSecondInterface())
  13:                  .Returns(4);
  14:   
  15:              int returnValue =
  16:                  SomeClass.MultipleInterfaceUser<SomeClassImplementingInterfaces>(c.Object);
  17:   
  18:              Assert.That(returnValue, Is.EqualTo(6));
  19:          }

注意这里使用As方法,增加一个指定的Interface到Mock.下面这个方法也可以Pass:

   1:          [Test]
   2:          public void MultipleInterfaceTest2()
   3:          {
   4:              Mock<SomeClassImplementingInterfaces> c =
   5:                  new Mock<SomeClassImplementingInterfaces>();
   6:   
   7:              c.Setup(m => m.SomeMethodOnFirstInterface()).Returns(2);
   8:              c.Setup(m => m.SomeMethodOnSecondInterface()).Returns(4);
   9:   
  10:              int returnValue =
  11:                  SomeClass.MultipleInterfaceUser<SomeClassImplementingInterfaces>(c.Object);
  12:   
  13:              Assert.That(returnValue, Is.EqualTo(6));
  14:          }

 

您可以下载Moq,NUnit测试以上代码.Moq框架对UnitTest,TDD有着极大的意义,在后面有时间会介绍更多.希望对您有帮助.


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2010-09-04 16:32  PetterLiu  阅读(2998)  评论(0编辑  收藏  举报