簡體   English   中英

如何通過 Moq 使用類 Object in out 參數

[英]How to use class Object in out parameter with Moq

我試圖模擬我的服務的一些功能。 代碼是這樣的。

public interface IObj {
       public bool anotherMethod(string input, out string responseString);
}

public class SomeClass {
      public bool SomeMethod(string input, out IObj outputObj) {
             // some logic
             if (logic is correct) {
                  outputObj = // object of IObj
                  return true;
             }
             outputObj = null;
             return false;
       }
}

public class Service {
       public void executingMethod(){
               if (this.someClassObj.SomeMethod(this.inputString, out outputObj) {
                   if (outputObj.anotherMethod(this.anotherInputString, out responseString) 
                    {
                        // some business logic
                    }

               }
       }

}

現在我想使用 Moq 和 xUnit 模擬executingMethod方法行為 vai UnitTest 的方法。 但是在嘲笑時,我遇到了out參數的問題。 通過這種方式,我試圖模擬這種行為。

[Fact]
public void MockingMethod(){
       // Arrange
       Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
       Mock<IObj> mockIObj = new Mock<IObj>();
       string mockedResponse = "someResponse";

       // here i am getting the issue, as out is expecting actual object not mocked object.
       mockSomeClass.Setup(s => s.SomeMethod(It.IsAny<string>(), out mockIObj).Returns(true);
       mockIObj.Setup(s => s.anotherMethod(It.IsAny<string(), out mockedResponse).Returns(true);

}

任何幫助都感激不盡。 TIA。

我也嘗試按照@Roman 的建議使用。 mockSomeClass.Setup(s => s.SomeMethod(It.IsAny<string>(), out mockIObj.Object).Returns(true);

但它拋出此錯誤->“屬性或索引器可能不會作為 out 或 ref 參數傳遞”

試試“mockIObj.Object”。 這應該傳入模擬對象而不是模擬實例

我找到了解決此問題的其他方法。 這個方法public bool SomeMethod(string input, out IObj outputObj)正在調用另一個方法,比如這個public bool oneAnotherMethod(string input, out string outputResponse)這個方法解決了這個問題。

我不知道模擬內部調用可以在調用鏈之上傳播。

感謝所有的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM