How to mock an out parameter with It.IsAny<> with Moq?
Asked Answered
M

2

8

I would like to verify that a method is only called once.

mock.Verify(x => x.Method("String", out It.IsAny<StringBuilder>()), Times.Once);

I don't care about the second parameter, it could be anything.

I get the following error message because of the out parameter:

'out' argument must be an assignable variable, field or array element

Mycetozoan answered 23/4, 2018 at 10:12 Comment(0)
S
3

You can verify for Any by using It.Ref<StringBuilder>.IsAny. In your case the solution would be the following:

mock.Verify(x => x.Method("String", out It.Ref<StringBuilder>.IsAny), Times.Once);

This function was added in Moq 4.8.0-rc1

Sourdough answered 14/4, 2023 at 11:25 Comment(0)
B
1

Try following the error message instructions and putting the out parameter in a variable.

var builder = new StringBuilder();
mock.Verify(x => x.Method("String", out builder), Times.Once);

Here is a full example that passes when tested.

[TestClass]
public class ExampleTest {
    public interface IInterface {
        void Method(string p, out StringBuilder builder);
    }

    public class MyClass {
        private IInterface p;

        public MyClass(IInterface p) {
            this.p = p;
        }

        public void Act() {
            var builder = new StringBuilder();
            p.Method("String", out builder);
        }
    }

    [TestMethod]
    public void Should_Ignore_Out() {
        //Arrange
        var mock = new Mock<IInterface>();
        var sut = new MyClass(mock.Object);

        //Act
        sut.Act();

        //Assert
        var builder = new StringBuilder();
        mock.Verify(x => x.Method("String", out builder), Times.Once);
    }
}
Bloat answered 23/4, 2018 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.