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
Hope someone can help with this problem.
I am using the Community Edition of TypeMock with .NET 2.0.
I have a concrete class with an interface in the constructor.
The interface has an event which is handled within the concrete class.

Public Class TestClass
Private WithEvents m_ConcreteITestInterface As ITestInterface
'Private WithEvents _view As IViewEditInvMasterExtended
Public Event Save()

Public Sub New(ByVal View As ITestInterface)
If View Is Nothing Then
Throw New ArgumentNullException("View must not be nothing.")
Else
m_ConcreteITestInterface = View '===> FAILS HERE
End If
End Sub

Private Sub _view_Save() Handles m_ConcreteITestInterface.Save
End Sub

End Class

Here is the interface
Public Interface ITestInterface
Property GetTestValue() As String
Event Save()
End Interface

<NUnit.Framework.TestFixture()> _
Public Class NUnitTests
<Test()> _
Public Sub RunTest()
MockManager.Init()
Dim Mock As MockObject = MockManager.MockObject(GetType(ITestInterface))
Dim ITestInterfaceMock As ITestInterface = Mock.Object
Dim TestClassInstance As New TestClass(ITestInterfaceMock)

End Sub
End Class

When I try to mock the interface, I am getting an exception at the line where the interface is getting copied.
The problem is because of the line "Handles m_ConcreteITestInterface.Save". If I removed that, then there is no error.
Am I missing something? Is there any way to mock this with TypeMock or do I have to go back to the traditional mocking and create a stub for the interface?

Thanks for any help.
asked by jimmyseow123 (4.6k points)

2 Answers

0 votes
Jimmy,
When you set m_ConcreteITestInterface to View, you are actually adding an event listener. Because MockObjects are Strict by default (that is all methods must be expected) the test fails.
Here is how you can solve it:
<Test()> _
Public Sub RunTest()
  MockManager.Init()
  Dim Mock As MockObject = MockManager.MockObject(GetType(ITestInterface))
   ' Expect the event to be added
   Mock.ExpectAddEvent("Save")

   Dim ITestInterfaceMock As ITestInterface = Mock.Object
   Dim TestClassInstance As New TestClass(ITestInterfaceMock)
End Sub


Once you have that you can take the tests further and actually Raise the event. Here is how:
Save the event handle:
Dim SaveEvent As MockedEvent = Mock.ExpectAddEvent("Save")

Then you can raise the event and verify that your code works by:
SaveEvent.Fire()
answered by scott (32k points)
0 votes
Fantastic!
Thanks a lot!
TypeMock is the best mock available!
answered by jimmyseow123 (4.6k points)
...