Home > Back-end >  How to use class Object in out parameter with Moq
How to use class Object in out parameter with Moq

Time:06-22

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. But while mocking I am getting issue with out parameter. 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.

I tried to use as suggested by @Roman as well. 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"

CodePudding user response:

Try “mockIObj.Object” . This should pass in the mocked object rather than the mocked instance

CodePudding user response:

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.

I was not knowing that mocking internal calls can propagate above the calling chain.

Thanks for all the help.

  • Related