Dear TypeMock Team,
I am experiencing a problem when I try to use "ExpectRemoveEvent" method on my mocked object, but the event handler was not added yet.
Please see below. The example I prepared to show this problem is very simple, it consist of a simple class:
public class ClassB {
public event Action<string> StatusChanged;
void SingalStatusChanged() {
if (StatusChanged != null) {
StatusChanged("Changed");
}
}
}
And a class that utilizes ClassB object:
public class ClassA {
ClassB _myObject;
public ClassA(ClassB myObject) {
_myObject = myObject;
}
public void Initialize(ClassB myObject) {
Dispose();
_myObject = myObject;
_myObject.StatusChanged += _classBObject_StatusChanged;
}
void Dispose() {
if (_myObject != null) {
_myObject.StatusChanged -= _classBObject_StatusChanged;
_myObject = null;
}
}
void _classBObject_StatusChanged(string obj) {
}
}
The class below ( ClassA ) was especially prepared to show the problem I am seeing.
And now the test:
[TestFixture]
public class TestClassA {
ClassA _classAObject;
Mock<ClassB> _myObjectMock;
[SetUp]
public void SetUp() {
_myObjectMock = MockManager.MockObject<ClassB>();
_classAObject = new ClassA(_myObjectMock.MockedInstance);
}
[Test]
public void TestInitialize() {
_myObjectMock.ExpectRemoveEvent("StatusChanged");
_myObjectMock.ExpectAddEvent("StatusChanged");
_classAObject.Initialize(_myObjectMock.MockedInstance);
}
[TearDown]
public void TearDown() {
_classAObject = null;
}
}
When the test is run a null reference exception occurs in the line of the code, where the EventHandler is removed ( ClassA, Disppose method ) :
_myObject.StatusChanged -= _classBObject_StatusChanged;
I do not exactly understand why this is happening. I am not getting any exception when I call the Initialize method:
class Program {
static void Main(string[] args) {
ClassA classAObject = new ClassA(new ClassB());
classAObject.Initialize(new ClassB());
}
}
Which means such operation is allowed.
There is a workaround for this problem I have managed to figure out:
[Test]
public void TestInitialize() {
//here is the workaround
_myObjectMock.ExpectAddEvent("StatusChanged");
_myObjectMock.MockedInstance.StatusChanged += MockedInstance_StatusChanged;
//
_myObjectMock.ExpectRemoveEvent("StatusChanged");
_myObjectMock.ExpectAddEvent("StatusChanged");
_classAObject.Initialize(_myObjectMock.MockedInstance);
}
void MockedInstance_StatusChanged(string obj) {
}
However this is not a solution that satisifes our needs - the code we are testing is really complex and causes that a lot of redundant code is added to the tests.
Could You please help?