简体   繁体   English

如何通过 Moq 使用类 Object in out 参数

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

I was trying to Mock some some functionality of my Services.我试图模拟我的服务的一些功能。 The code goes like this.代码是这样的。

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
                    }

               }
       }

}

Now i want to Mock the method executingMethod behaviour vai UnitTest using Moq and xUnit.现在我想使用 Moq 和 xUnit 模拟executingMethod方法行为 vai UnitTest 的方法。 But while mocking I am getting issue with out parameter.但是在嘲笑时,我遇到了out参数的问题。 In this way I am trying to mock the behaviour.通过这种方式,我试图模拟这种行为。

[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);

}

Any help will be much appreciated.任何帮助都感激不尽。 TIA. TIA。

I tried to use as suggested by @Roman as well.我也尝试按照@Roman 的建议使用。 mockSomeClass.Setup(s => s.SomeMethod(It.IsAny<string>(), out mockIObj.Object).Returns(true);

but it is throwing this error -> "A property or indexer may not be passed as out or ref parameter"但它抛出此错误->“属性或索引器可能不会作为 out 或 ref 参数传递”

Try “mockIObj.Object” .试试“mockIObj.Object”。 This should pass in the mocked object rather than the mocked instance这应该传入模拟对象而不是模拟实例

I Found other way to resolve this issue.我找到了解决此问题的其他方法。 This method public bool SomeMethod(string input, out IObj outputObj) was calling one another method like this public bool oneAnotherMethod(string input, out string outputResponse) mocking this method resolve the issue.这个方法public bool SomeMethod(string input, out IObj outputObj)正在调用另一个方法,比如这个public bool oneAnotherMethod(string input, out string outputResponse)这个方法解决了这个问题。

I was not knowing that mocking internal calls can propagate above the calling chain.我不知道模拟内部调用可以在调用链之上传播。

Thanks for all the help.感谢所有的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM