验证传入的模拟对象的设置

时间:2016-04-21 01:01:08

标签: c# .net visual-studio nunit moq

我正在测试我的班级

public class myclass
{
  private IAwesome awesomeObject;
  public myclass(IAwesome awesomeObject)
  {
     this.awesomeObject = awesomeObject;
  }


  public void MethodUnderTest()
  {
      this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
  }
}

我这样做的方式是:

//Arrange
var mockAwesome = new Mock<IAwesome>();
mockAwesome.Setup(x=>x.RunSomething()).Returns ... Verify()...;
//Act
var sut = new myclass(mockAwesome.object);
sut.MethodUnderTest();
//Assert
mockAwesome.Verify();

我得到的例外是:

  

System.NotSupportedException:Expression引用一个方法   不属于模拟对象:x =&gt; x.RunSomething

是否无法测试在我传入类的模拟对象上是否执行了特定方法,该类现在是该类的私有成员的一部分?

2 个答案:

答案 0 :(得分:1)

测试时,对我来说效果很好......

尝试这种方法,看看是否有任何不同的结果...

void Main()
{
    IAwesome awesome    = Mock.Of<IAwesome>();
    Mock<IAwesome> mock = Mock.Get(awesome);
    mock.Setup(m => m.RunSomething());

    MyClass myClass = new MyClass(awesome);
    myClass.MethodUnderTest();

    mock.Verify(m => m.RunSomething(), Times.Once);
}

public interface IAwesome
{
    void RunSomething();
}

public class MyClass
{
    private IAwesome awesomeObject;

    public myclass(IAwesome awesomeObject)
    {
        this.awesomeObject = awesomeObject;
    }

    public void MethodUnderTest()
    {
        this.awesomeObject.RunSomething();
    }
}

答案 1 :(得分:1)

将设置行修改为mockAwesome.Setup(x=>x.RunSomething()).Verifiable(),它应该适用于您提供的示例。

[TestClass]
public class MoqVerificationTest {
    [TestMethod]
    public void Moq_Should_Verify_Setup() {
        //Arrange
        var mockAwesome = new Mock<IAwesome>();
        mockAwesome.Setup(x => x.RunSomething()).Verifiable();
        //Act
        var sut = new myclass(mockAwesome.Object);
        sut.MethodUnderTest();
        //Assert
        mockAwesome.Verify();
    }

    public interface IAwesome {
        void RunSomething();
    }

    public class myclass {
        private IAwesome awesomeObject;
        public myclass(IAwesome awesomeObject) {
            this.awesomeObject = awesomeObject;
        }
        public void MethodUnderTest() {
            this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
        }
    }
}

要确认,请在示例类中注释this.awesomeObject.RunSomething()并再次运行测试。它会失败,因为您将RunSomething设置为Verifiable()并且未使用它。