chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
How can I do this using Natural Mocking?

Imports MbUnit.Framework
Imports TypeMock
<TestFixture()> _
Public Class StringListTest
    <Test()> _
    Public Sub SomeTest()
        Dim mock As Mock = MockManager.Mock(GetType(StringList), Constructor.NotMocked)
        mock.ExpectAndReturn("Fill", New DynamicReturnValue(AddressOf Me.DynamicFill))

        'Execute code:
        Dim list As New StringList

        list.doSomething()

        'Verify results:
        Assert.AreEqual(2, list.Count)
        Assert.AreEqual("mockString1", list(0))
    End Sub

    Function DynamicFill(ByVal parameters() As Object, ByVal context As Object) As Object
        Dim list As StringList = DirectCast(context, StringList)
        list.Add("mockString1")
        list.Add("mockString2")
        Return Nothing
    End Function
End Class

Public Class StringList
    Inherits List(Of String)
    Public Sub Fill()
        Me.Add("t1")
        Me.Add("t2")
    End Sub

    Public Sub doSomething()
        Me.Fill()
        For Each s As String In Me
            Trace.WriteLine(s)
        Next
    End Sub
End Class
asked by OrjanM (600 points)

1 Answer

0 votes
Hi

Here is how its done in natural mocks:
    <Test()> _
    Public Sub SomeTest2()

        Using recorder As New RecordExpectations
            Dim mockList As New StringList
            'this is instead of Constructor.NotMocked
            recorder.CallOriginal()
            mockList.Fill()
            'Set the return value
            recorder.Return(New DynamicReturnValue(AddressOf Me.DynamicFill))
        End Using

        'Execute code:
        Dim list As New StringList

        list.doSomething()

        'Verify results:
        Assert.AreEqual(2, list.Count)
        Assert.AreEqual("mockString1", list(0))
    End Sub


Generally speaking you call the methods you want to mock
inside the 'Using' block (Just like you will do in production code)
and use the recorder object to set the expectations.
answered by ohad (35.5k points)
...