Search code examples
vb.netnunitmoq

Mock class to return By Reference in VB


Let me have class like this:

Public Class MyClass
    Implements IMyClass

    Public Function GetSomething(firstParameter As String, secondParameter As String, ByRef thirdParameter As String) As Boolean Implements IMyClass.GetSomething
        thirdParameter = _secondDependency.GetSomething(firstParameter, thirdParameter)
        Return True
    End Function

    'rest of class

Now in my test I am using NUnit and Moq lib and want to setup this mocked class

_mockMyClass.Setup(
            Function(myClass) myClass.GetSomething(It.IsAny(Of String), It.IsAny(Of String), It.IsAny(Of String))).Returns(True)

But I do not know how to setup thirdParameter to be set to some string I define, since it is passed by reference and I do not know how to do that with moq. I want to do this without changing the mocked class.


Solution

  • After some digging I came with this which does the work:

    _mockMyClass.
                Setup(Function(myClass) myClass.GetSomething(It.IsAny(Of String), It.IsAny(Of String), It.IsAny(Of String))).
                Callback(
                    Sub(firstParameter As String, secondParameter As String, ByRef thirdParameter As String)
                        thirdParameter = "someString"
                    End Sub).
    

    It should be noted that this works in Moq 4.8+