Download source code...
The pattern I have used successfuly is to add a handler before invoking your test subject, then setting some private member variables in the handler and inspecting their values.
Whenever I do this, I typically clear the privates in a TestInitialize to ensure if someone else forgets to do it, I don't get into trouble.
There are some event handling facilities in Typemock, see Mock Events in the help file.
Tim
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace
EventTesting{
public class Subject
{
public delegate void LibraryFilePathChangedEventDelegate(string Oldpath, string Newpath);
public event LibraryFilePathChangedEventDelegate LibraryFilePathChangedEvent;string m_libraryLocation;
/// <summary>
/// A method to change the location of the XML file to which the library is serialized/deserialized.
/// </summary>
/// <param name="newLibraryLocation"></param>public void SetLibraryLocation(string newLibraryLocation)
{
string oldLocation = m_libraryLocation;
m_libraryLocation = newLibraryLocation;
if (this.LibraryFilePathChangedEvent != null)
{
this.LibraryFilePathChangedEvent(null, m_libraryLocation);
}
// need to mock this so it is not null? this.LibraryFilePathChangedEvent(oldLocation, newLibraryLocation); // I want to test that this gets fired
}
}
[TestClass]
public class SubjectTest
{
[TestMethod]
[
Description("Proves SetLibraryLocation fires the LibraryFilePathChangedEvent as expected.")]public void SetLibraryLocationRaiseEvent()
{
Subject target = new Subject();
string expectedNewPath = "this is my new path.";string expectedOldPath = null ; target.LibraryFilePathChangedEvent += new Subject.LibraryFilePathChangedEventDelegate(target_LibraryFilePathChangedEvent);
// set to a sentinel value
// could be set or cleared in TestInitialize() method.m_Oldpath = "ERROR!" ;m_Oldpath = "ERROR!" ;
target.SetLibraryLocation(expectedNewPath);
Assert.AreEqual<string>(expectedOldPath, m_Oldpath);Assert.AreEqual<string>(expectedNewPath, m_Newpath);
}
string m_Oldpath ;string m_Newpath ;void target_LibraryFilePathChangedEvent(string Oldpath, string Newpath)
{
m_Oldpath = Oldpath;
m_Newpath = Newpath;
}
}
}