2016-04-21 58 views
1

我測試我的課在嘲笑對象通過驗證設置

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:表達式引用 不屬於模擬對象的方法:x => x.RunSomething

難道不可能測試一個特定的方法是在我傳入一個類的模擬對象上執行的,它現在是該類的私有成員的一部分嗎?

+0

將設置行修改爲'mockAwesome.Setup(x => x.RunSomething())。Verifiable()',它應該適用於您提供的示例。要確認,請在示例類中註釋掉'this.awesomeObject.RunSomething()'並運行測試。它會失敗,因爲你將'RunSomething'設置爲'Verifiable()'並且它沒有被使用。 – Nkosi

回答

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()並且它未被使用。

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(); 
    } 
}