Verifying event registration using Moq - c#

I'm developing an asp.net (classic) application trying to implement the MVP pattern using this example. In trying to unit test my presenter and using the following pattern, the psuedocode for which looks like so
//base view interface
public interface IView
{
event EventHandler Init;
event EventHandler Load;
bool IsPostBack { get; }
void DataBind();
bool IsValid { get;}
}
//presenter psuedo code
public class SomePresenter
{
public SomePresenter(ISomeDomainService service, IView someView)
{
...
//HOW DO WE TEST/VERIFY THAT THIS REGISTRATION OCCURS?
someView.Init += OnInit;
someView.Load += OnLoad;
}
}
...
//consuming code that exercises the above code, that needs to be tested
var presenter = new SomePresenter(someDomainService, someView);
How do I verify that the presenter is doing what is expected i.e. registering for the Init and Load events? While this is easily done in the Phil Haack's example using Rhino mocks...
[Test]
public void VerifyAttachesToViewEvents()
{
viewMock.Load += null;
LastCall.IgnoreArguments();
viewMock.PostSaved += null;
LastCall.IgnoreArguments();
mocks.ReplayAll();
new PostEditController(viewMock,
this.dataServiceMock);
mocks.VerifyAll();
}
... how can we do this using MOQ?

The moq 4.13 introduced this feature. Now it is possible to verify if add\remove has been invoked. Therefore four new methods have been introduced:
SetupAdd
SetupRemove
VerifyAdd
VerifyRemove
Example
var mock = new Mock<IAdder<EventArgs>>();
mock.SetupAdd(m => m.Added += (sender, args) => { });
mock.Object.Added += (sender, args) => { };
mock.Object.Added += (sender, args) => { };
mock.VerifyAdd(m => m.Added += It.IsAny<EventHandler>(), Times.Exactly(2));
NB: Notice that in order to verify at least one setup should be added. The reason is to keep backward compatibility with the older version of moq.

It would appear that this functionality is not currently available in moq, but may appear in a future version (I had a look in the 4.0.812.4 beta, but it doesn't seem to be there).
It may be worth asking the question, "why does SomePresenter need to subscribe to the View's Load and Init events?" Presumably it is because the SomePresenter class needs to respond to those events. So it might be better to use the Raise method on your Mock<IView> to raise the Load and Init events, and then assert that SomePresenter did the right thing in response to them.

I know it's maybe too late for #Dilip, but this answer can be helpful for those who are trying to do the same.
Here is the test class
public delegate void SubscriptionHandler<T>(string name, T handler);
public class SomePresenterTest
{
[Test]
public void Subscription_Test()
{
var someServiceMock = new Mock<ISomeDomainService>();
var viewMock = new Mock<IView>();
//Setup your viewMock here
var someView = new FakeView(viewMock.Object);
EventHandler initHandler = null;
someView.Subscription += (n, h) => { if ((nameof(someView.Init)).Equals(n)) initHandler=h; };
Assert.IsNull(initHandler);
var presenter = new SomePresenter(someServiceMock.Object, someView);
Assert.IsNotNull(initHandler);
Assert.AreEqual("OnInit", initHandler.Method?.Name);
}
}
FakeView is a decorator implemented as follow (pay attention to Events:Init/Load{add;remove}):
public class FakeView : IView
{
public event SubscriptionHandler<EventHandler> Subscription;
public event SubscriptionHandler<EventHandler> Unsubscription;
private IView _view;
public FakeView(IView view)
{
Assert.IsNotNull(view);
_view = view;
}
public bool IsPostBack => _view.IsPostBack;
public bool IsValid => _view.IsValid;
public event EventHandler Init
{
add
{
Subscription?.Invoke(nameof(Init), value);
_view.Init += value;
}
remove
{
Unsubscription?.Invoke(nameof(Init), value);
_view.Init -= value;
}
}
public event EventHandler Load
{
add
{
Subscription?.Invoke(nameof(Load), value);
_view.Init += value;
}
remove
{
Unsubscription?.Invoke(nameof(Load), value);
_view.Init -= value;
}
}
public void DataBind()
{
_view.DataBind();
}
}

I spent some time with this question and the solution which I'm using in my project is:
Unit test:
// Arrange
TestedObject.Setup(x => x.OnEvent1());
TestedObject.Setup(x => x.OnEvent2());
// Act
TestedObject.Object.SubscribeEvents();
TestedObject.Raise(x => x.Event1 += null);
TestedObject.Raise(x => x.Event2 += null);
// Assert
TestedObject.Verify(x => x.OnEvent1(), Times.Once());
TestedObject.Verify(x => x.OnEvent2(), Times.Once());
Tested method:
this.Event1 += OnEvent1;
this.Event2 += OnEvent2;
So, first you have to mock the methods which you will assign the events, after you call the method which you want to test, and finally raise all subscribed events. If the event is really subscribed, you can check with Moq if the assigned method is called.
GLHF!

Related

Unit Test INotifyPropertyChanged using Rhino Mocks

I have a class that implements INotifyPropertyChanged and I need to test if this interface is implemented correctly. I want to do this using a Rhino Mock object.
class MyClass : INotifyPropertyChanged
{
public int X
{
get => ...;
set => ... // should check if value changes and raise event PropertyChanged
}
}
What I want to test, is that when X changes value, that event PropertyChanged is called exactly once, with the proper parameters.
MyClass testObject = new MyClass();
// the mock:
PropertyChangedEventHandler a = MockRepository.GenerateMock<PropertyChangedEventHandler>();
testObject.PropertyChanged += a;
// expect that the mock will be called exactly once, with the proper parameters
a.Expect( (x) => ???)
.Repeat()
.Once();
// change X, and verify that the event handler has been called exactly once
testObject.X = testObject.X + 1;
a.VerifyAllExpectations(); ???
I think I'm on the right path, but I can't get it working.
Sometimes, there really is no need to use a mock if there are not knock-on effects of using the real thing.
The following simple example creates an instance of the delegate and verifies the expected behavior
What I want to test, is that when X changes value, that event PropertyChanged is called exactly once, with the proper parameters.
[TestClass]
public class MyClassTests {
[TestMethod]
public void Should_Call_PropertyChanged_Once() {
//Arrange
//Store calls
IDictionary<string, int> properties = new Dictionary<string, int>();
PropertyChangedEventHandler handler = new PropertyChangedEventHandler((s, e) => {
if (!properties.ContainsKey(e.PropertyName))
properties.Add(e.PropertyName, 0);
properties[e.PropertyName]++;
});
MyClass testObject = new MyClass();
testObject.PropertyChanged += handler;
string expectedPropertyName = nameof(MyClass.X);
int expectedCount = 1;
//Act
testObject.X = testObject.X + 1;
//Assert - using FluentAssertions
properties.Should().ContainKey(expectedPropertyName);
properties[expectedPropertyName].Should().Be(expectedCount);
}
class MyClass : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged = delegate { };
void raisePropertyChanged([CallerMemberName]string propertyName = null) {
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
int x;
public int X {
get => x;
set {
if (value != x) {
x = value;
raisePropertyChanged();
}
}
}
}
}

Constructor that takes any delegate as a parameter

Here's the simplified case. I have a class that stores a delegate that it will call on completion:
public class Animation
{
public delegate void AnimationEnd();
public event AnimationEnd OnEnd;
}
I have another utility class that I want to subscribe to various delegates. On construction I want itself to register to the delegate, but other than that it doesn't care about the type. The thing is, I don't know how to express that in the type system. Here's my pseudo-C#
public class WaitForDelegate
{
public delegateFired = false;
// How to express the generic type here?
public WaitForDelegate<F that's a delegate>(F trigger)
{
trigger += () => { delegateFired = true; };
}
}
Thanks in advance!
Thanks to Alberto Monteiro, I just use System.Action as the type for the event. My question now is, how to pass the event to the constructor so it can register itself? This might be a very dumb question.
public class Example
{
Animation animation; // assume initialized
public void example()
{
// Here I can't pass the delegate, and get an error like
// "The event can only appear on the left hand side of += or -="
WaitForDelegate waiter = new WaitForDelegate(animation.OnEnd);
}
}
I'm afraid you can't do what you're asking.
First up, you can't constrain by delegates. The closest code to legal C# is this:
public class WaitForDelegate<F> where F : System.Delegate
{
public bool delegateFired = false;
public WaitForDelegate(F trigger)
{
trigger += () => { delegateFired = true; };
}
}
But it won't compile.
But the bigger problem is that you can't pass delegates around like this anyway.
Consider this simplified class:
public class WaitForDelegate
{
public WaitForDelegate(Action trigger)
{
trigger += () => { Console.WriteLine("trigger"); };
}
}
I then try to use it like this:
Action bar = () => Console.WriteLine("bar");
var wfd = new WaitForDelegate(bar);
bar();
The only output from this is:
bar
The word trigger doesn't appear. This is because delegates are copied by value so that the line trigger += () => { Console.WriteLine("trigger"); }; is only attaching the handler to trigger and not bar at all.
The way that you can make all of this work is to stop using events and use Microsoft's Reactive Extensions (NuGet "Rx-Main") which allows you to turn events into LINQ-based IObservable<T> instances that can get passed around.
Here's how my example code above would then work:
public class WaitForDelegate
{
public WaitForDelegate(IObservable<Unit> trigger)
{
trigger.Subscribe(_ => { Console.WriteLine("trigger"); });
}
}
And you now call it like:
Action bar = () => Console.WriteLine("bar");
var wfd = new WaitForDelegate(Observable.FromEvent(h => bar += h, h => bar -= h));
bar();
This now produces the output:
bar
trigger
Notice that the Observable.FromEvent call contains the code to attach and detach the handler in a scope that has access to do so. It allows the final subscription call to be unattached with a call to .Dispose().
I've made this class quite simple, but a more complete version would be this:
public class WaitForDelegate : IDisposable
{
private IDisposable _subscription;
public WaitForDelegate(IObservable<Unit> trigger)
{
_subscription = trigger.Subscribe(_ => { Console.WriteLine("trigger"); });
}
public void Dispose()
{
_subscription.Dispose();
}
}
An alternative if you don't want to go for the full use of Rx is to do this:
public class WaitForDelegate : IDisposable
{
private Action _detach;
public WaitForDelegate(Action<Action> add, Action<Action> remove)
{
Action handler = () => Console.WriteLine("trigger");
_detach = () => remove(handler);
add(handler);
}
public void Dispose()
{
if (_detach != null)
{
_detach();
_detach = null;
}
}
}
You call it like this:
Action bar = () => Console.WriteLine("bar");
var wfd = new WaitForDelegate(h => bar += h, h => bar -= h);
bar();
That still does the correct output.
In .NET there is already a delegate that doesn't receive no parameters, it is the Action
So you Animation class could be like that:
public class Animation
{
public event Action OnEnd;
}
But you can pass events as parameters, if you try that you will receive this compilation error
The event can only appear on the left hand side of += or -="
So lets create a interface, and declare the event there
public interface IAnimation
{
event Action OnEnd;
}
Using the interface approach you have no external dependencies and you can have many classes that implements that, also is a good practice, depends of abstractions instead concrete types. There is acronym called SOLID that explain 5 principles about better OO code.
And then your animation class implements that
Obs.: The CallEnd method is just for test purpose
public class Animation : IAnimation
{
public event Action OnEnd;
public void CallEnd()
{
OnEnd();
}
}
And now you WaitForDelegate will receive a IAnimation, so the class can handle any class that implements the IAnimation class
public class WaitForDelegate<T> where T : IAnimation
{
public WaitForDelegate(T animation)
{
animation.OnEnd += () => { Console.WriteLine("trigger"); };
}
}
Then we can test the code that we did with the following code
public static void Main(string[] args)
{
var a = new Animation();
var waitForDelegate = new WaitForDelegate<IAnimation>(a);
a.CallEnd();
}
The result is
trigger
Here is the working version on dotnetfiddle
https://dotnetfiddle.net/1mejBL
Important tip
If you are working with multithread, you must take some caution to avoid Null Reference Exception
Let's look again the CallEnd method that I've added for test
public void CallEnd()
{
OnEnd();
}
OnEnd event could have not value, and then if you try to call it, you will receive Null Reference Exception.
So if you are using C# 5 or lower, do something like this
public void CallEnd()
{
var #event = OnEnd;
if (#event != null)
#event();
}
With C# 6 it could be like that
public void CallEnd()
=> OnEnd?.Invoke();
More explanation, you could have this code
public void CallEnd()
{
if (OnEnd != null)
OnEnd();
}
This code that is above, probably make you think that you are safe from Null Reference Exception, but with multithread solution, you aren't. That's because the OnEnd event could be set to null between the execution of if (OnEnd != null) and OnEnd();
There is a nice article by Jon Skeet about it, you cann see Clean event handler invocation with C# 6

Raising complex event using Moq in C#

The following code should be self explanetory: we have an adaptor, who consumes events from the transport (layer), which holds the MessageRegistrar (object type because we can't tell it's type, and basically because this is legacy code :-) ). The transport layer have a concrete which have an event.
I want to test a case where the event is triggered, so..
After hours of trying to figure why it won't pass, I present the following challenge:
[TestFixture]
public class AdaptorTests
{
public delegate void TracksEventHandler(object sender, List<int> trklst);
public class MyEventHolder
{
public virtual event TracksEventHandler EventName;
}
public interface ITransport
{
object MessageRegistrar { get; }
}
public class MyTransport : ITransport
{
private readonly MyEventHolder m_eventHolder;
public MyTransport(MyEventHolder eventHolder)
{
m_eventHolder = eventHolder;
}
public virtual object MessageRegistrar
{
get { return m_eventHolder; }
}
}
public class MyAdaptor
{
private readonly ITransport m_transport;
public MyAdaptor(ITransport transport)
{
EventTriggered = false;
m_transport = transport;
}
public void Connect()
{
MyEventHolder eventHolder = m_transport.MessageRegistrar as MyEventHolder;
if (eventHolder != null)
eventHolder.EventName += EventHolderOnEventName;
}
private void EventHolderOnEventName(object sender, List<int> trklst)
{
EventTriggered = true;
}
public bool EventTriggered { get; private set; }
}
[Test]
public void test1()
{
Mock<MyEventHolder> eventHolderMock = new Mock<MyEventHolder> {CallBase = true};
Mock<MyTransport> transportMock = new Mock<MyTransport>(eventHolderMock.Object) {CallBase = true};
MyAdaptor adaptor = new MyAdaptor(transportMock.Object);
adaptor.Connect();
MyEventHolder eventHolder = transportMock.Object.MessageRegistrar as MyEventHolder;
Mock.Get(eventHolder).Raise(eh => eh.EventName += null, new List<int>());
Assert.IsTrue(adaptor.EventTriggered);
}
[Test]
public void test2()
{
Mock<MyEventHolder> eventHolderMock = new Mock<MyEventHolder> { CallBase = true };
Mock<MyTransport> transportMock = new Mock<MyTransport>(eventHolderMock.Object) { CallBase = true };
MyAdaptor adaptor = new MyAdaptor(transportMock.Object);
adaptor.Connect();
MyEventHolder eventHolder = transportMock.Object.MessageRegistrar as MyEventHolder;
Mock.Get(eventHolder).Raise(eh => eh.EventName += null, null, new List<int>());
Assert.IsTrue(adaptor.EventTriggered);
}
}
My question is: why wont the test (at least one of them) pass?
EDIT #151217-0822 Addded 'adaptor.Connect()' to the original post (still won't fix the issue).
WORKAROUND
Credits to #Patrick Quirk: Thanks!!
For those encountering the same issue: after I understood what Patrick-Quirk detected, and trying couple of failed workarounds, I've ended up adding the following verified fix: 'eventHolder.FireEventNameForTestings(new List());':
public class MyEventHolder
{
public virtual event TracksEventHandler EventName;
public virtual void FireEventNameForTestings(List<int> trklst)
{
TracksEventHandler handler = EventName;
if (handler != null)
handler(this, trklst);
}
}
[Test]
public void test3()
{
Mock<MyEventHolder> eventHolderMock = new Mock<MyEventHolder> { CallBase = true };
Mock<MyTransport> transportMock = new Mock<MyTransport>(eventHolderMock.Object) { CallBase = true };
MyAdaptor adaptor = new MyAdaptor(transportMock.Object);
adaptor.Connect();
MyEventHolder eventHolder = transportMock.Object.MessageRegistrar as MyEventHolder;
eventHolder.FireEventNameForTestings(new List<int>());
Assert.IsTrue(adaptor.EventTriggered);
}
HTH..
It seems that CallBase and Raise() have an unexpected (to me) interaction.
When you are attaching an event handler to a virtual event on a mock, you go through this code in Moq:
if (invocation.Method.IsEventAttach())
{
var delegateInstance = (Delegate)invocation.Arguments[0];
// TODO: validate we can get the event?
var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(4));
if (ctx.Mock.CallBase && !eventInfo.DeclaringType.IsInterface)
{
invocation.InvokeBase();
}
else if (delegateInstance != null)
{
ctx.AddEventHandler(eventInfo, (Delegate)invocation.Arguments[0]);
}
return InterceptionAction.Stop;
}
You can see that if CallBase is true, then it will add your handler to the concrete object's event (via invocation.InvokeBase()). If CallBase is false, it will add it to an invocation list on the mock (via AddEventHandler). Now let's look at the code for Raise(), which gets the event object from the Expression and then calls DoRaise():
internal void DoRaise(EventInfo ev, EventArgs args)
{
// ... parameter validation
foreach (var del in this.Interceptor.InterceptionContext.GetInvocationList(ev).ToArray())
{
del.InvokePreserveStack(this.Object, args);
}
}
See the call to GetInvocationList()? That retrieves the invocation list from the mock that I mentioned above. This code never invokes the actual event on the base object.
So, it seems there's no way to raise an event on a mocked object where CallBase is set to true.
The only workaround I see, if you require CallBase being true, is to add a method to your concrete MyEventHolder to trigger your event. Obviously what you posted is a simplified example so I can't give you more guidance than that, but hopefully I've shown you why what you have does not work.

How to implement an event using Reactive Extensions

The Reactive Extensions allow you to easily subscribe to an event using Observable.FromEventPattern, but I can't find anything on how you might implement an event when you have an IObservable.
My situation is this: I need to implement an interface which contains an event. That event is supposed to be called whenever a certain value of my object changes, and for thread safety reasons I need to call this event on a certain SynchronizationContext. I am also supposed to call each event handler with the current value on registration.
public interface IFooWatcher
{
event FooChangedHandler FooChanged;
}
Getting an observable that does what I want is rather easy with Rx using BehaviorSubject:
public class FooWatcher
{
private readonly BehaviorSubject<Foo> m_subject;
private readonly IObservable<Foo> m_observable;
public FooWatcher(SynchronizationContext synchronizationContext, Foo initialValue)
{
m_subject = new BehaviorSubject<Foo>(initialValue);
m_observable = m_subject
.DistinctUntilChanged()
.ObserveOn(synchronizationContext);
}
public event FooChangedHandler FooChanged
{
add { /* ??? */ }
remove { /* ??? */ }
}
}
Now I am looking for an easy way to have the add and remove functions subscribe and unsubscribe the passed FooChangedHandler as an Observer<Foo> on m_observable. My current implementation looks similar to this:
add
{
lock (m_lock)
{
IDisposable disp = m_observable.Subscribe(value);
m_registeredObservers.Add(
new KeyValuePair<FooChangedHandler, IDisposable>(
value, disp));
}
}
remove
{
lock (m_lock)
{
KeyValuePair<FooChangedHandler, IDisposable> observerDisposable =
m_registeredObservers
.First(pair => object.Equals(pair.Key, value));
m_registeredObservers.Remove(observerDisposable);
observerDisposable.Value.Dispose();
}
}
However, I hope to find an easier solution, because I need to implement several of these events (of differing handler types). I tried to roll my own generic solution but it creates some additional problems that need to be worked around (in particular, how you generically work with a delegate that takes a parameter of T), so I would prefer to find an existing solution that bridges the gap in this direction - just as FromEventPattern does the reverse.
You could do this:
public event FooChangedHandler FooChanged
{
add { m_observable.ToEvent().OnNext += value; }
remove { m_observable.ToEvent().OnNext -= value; }
}
However, on the remove, I think perhaps you just may want to dispose of the subscription ... or perhaps get the Action from ToEvent() and store that as a member. Untested.
EDIT: You'll have to use Action instead of a FooChangedHandler delegate, however.
EDIT 2: Here's a tested version. I suppose you need to use FooChangedHandler, however, since you have a bunch of these pre-existing handlers?
void Main()
{
IObservable<Foo> foos = new [] { new Foo { X = 1 }, new Foo { X = 2 } }.ToObservable();
var watcher = new FooWatcher(SynchronizationContext.Current, new Foo { X = 12 });
watcher.FooChanged += o => o.X.Dump();
foos.Subscribe(watcher.Subject.OnNext);
}
// Define other methods and classes here
//public delegate void FooChangedHandler(Foo foo);
public interface IFooWatcher
{
event Action<Foo> FooChanged;
}
public class Foo {
public int X { get; set; }
}
public class FooWatcher
{
private readonly BehaviorSubject<Foo> m_subject;
public BehaviorSubject<Foo> Subject { get { return m_subject; } }
private readonly IObservable<Foo> m_observable;
public FooWatcher(SynchronizationContext synchronizationContext, Foo initialValue)
{
m_subject = new BehaviorSubject<Foo>(initialValue);
m_observable = m_subject
.DistinctUntilChanged();
}
public event Action<Foo> FooChanged
{
add { m_observable.ToEvent().OnNext += value; }
remove { m_observable.ToEvent().OnNext -= value; }
}
}
Given that you are already mixing the boundaries between reactive and more normal code, you could do a less reactive version. To start simply declare a normal event pattern
public event FooChangedHandler FooChanged;
protected void OnFooChanged(Foo)
{
var temp = FooChanged;
if (temp != null)
{
temp(new FooChangedEventArgs(Foo));
}
}
and then simply connect the observable to it in the constructor
m_Observable.Subscribe(foo => OnFooChanged(foo));
It's not very Rx but it is incredibly simple.

Why is this expectation failing?

I'm setting up some RhinoMock tests but I can't work out why my expectations are failing.
Here are the class/ interface I'm testing:
public class LogOn {
public virtual ILogOn View { get; set; }
public virtual IDataProvider DataProvider { get; set; }
public void SetUp(ILogOn view) {
this.View = view;
this.DataProvider = ... //using dependancy injection to do the data provider, so I want it faked in tests
}
public void SetUpEvents() {
this.View.Submit += new EventHandler(View_Submit);
}
void View_Submit(object sender, EventArgs e) {
if ( this.DataProvider.LogOn(this.Username) ) {
this.View.SubmitSuccess();
} else {
this.View.SubmitFailure("Username is incorrect");
}
}
}
public interface ILogOn {
string Username { get; set; }
event EventHandler Submit;
void SubmitSuccess();
void SubmitFailure(string message);
}
And here is my test method:
[TestMethod]
public void LogOnFailure() {
var dataProvider = MockRepository.CreateStub<DataProvider>();
var presenter = MockRepository.CreateMock<LogOn>();
var view = MockRepository.CreateMock<ILogOn>();
dataProvider.Expect(d => d.LogOn(null)).Return(true).Repeat.Any();
presenter.Expect(p => p.DataProvider).Return(dataProvider).Repeat.Any();
presenter.Expect(p => p.View).Return(view).Repeat.Any();
presenter.Expect(p => p.SetUpEvents()).CallOriginalMethod();
view.Expect(v => v.Username).Return("invalid").Repeat.Any();
view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));
presenter.SetUp(view);
presenter.SetUpEvents();
view.Raise(v => v.Submit += null, null, EventArgs.Empty);
presenter.VerifyAllExpectations();
view.VerifyAllExpectations();
}
The expectation that is failing is:
view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));
(indicated by view.VerifyAllExpectations)
It says that that method is never executed, but when using the debugger I can step through and LogOn.View is accessed, does call the SubmitFailure method (with that argument) and return correctly.
I can't work out what is missing as watching the code does indicate that everything is executed at the right time and with the right values.
Edit: Ok, so I let out the code which is why I was mocking the LogOn class, it has a dependancy of an external data provider (which I'm stubbing as I don't care how it works). My appologies, I thought I was making this clearer but just made is worse!
The LogOn class is your system under test, so you should not be mocking that. You want to test that the LogOn class behaves as it should in the case of an invalid username. You are able to determine the correct behavior by passing in a mocked view that sets up the scenario you want. Try changing your test to what I have below.
[TestMethod]
public void LogonFailure()
{
var presenter = new LogOn();
var view = MockRepository.CreateMock<ILogOn>();
view.Expect(v => v.Username).Return("invalid").Repeat.Any();
view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));
presenter.Setup(view);
view.Raise(v => v.Submit += null, null, EventArgs.Empty);
view.VerifyAllExpectations();
}

Categories