Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Testing events with NUnit mock objects
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using NUnit.Framework;
- using NUnit.Mocks;
- namespace NUnitTest
- {
- public delegate void LoggedInDelegate();
- public interface ISession
- {
- void LogIn(String username, String password);
- event LoggedInDelegate OnLoggedIn;
- }
- public class App
- {
- private bool loggedIn = false;
- private ISession sess;
- public bool LoggedIn
- {
- get
- {
- return loggedIn;
- }
- }
- public App(ISession sess)
- {
- this.sess = sess;
- sess.OnLoggedIn += HandleOnLoggedIn;
- }
- public void LogIn(String username, String password)
- {
- sess.LogIn(username, password);
- }
- public void HandleOnLoggedIn()
- {
- loggedIn = true;
- }
- }
- [TestFixture]
- public class AppTest
- {
- private String USERNAME = "Username";
- private String PASSWORD = "Password";
- private DynamicMock mockSess;
- private App app;
- [SetUp]
- public void TestInit()
- {
- // Create objects.
- mockSess = new DynamicMock(typeof(ISession));
- app = new App((ISession) mockSess.MockInstance);
- }
- [Test]
- public void TestLogin()
- {
- mockSess.Expect("LogIn", USERNAME, PASSWORD);
- app.LogIn(USERNAME, PASSWORD);
- mockSess.Verify();
- mockSess.Call("OnLoggedIn");
- Assert.IsTrue(app.LoggedIn);
- }
- }
- }
- [TestFixture]
- public sealed class TestStubbingEvents
- {
- [Test]
- public void FooReceivesEventFromBar()
- {
- BarStub bar = new BarStub();
- Foo foo = new Foo(bar);
- Assert.That(foo.EventReceived, Is.False);
- bar.RaiseBarEvent();
- Assert.That(foo.EventReceived, Is.True);
- }
- }
- internal class Foo
- {
- public bool EventReceived
- {
- get; set;
- }
- public Foo(IBar bar)
- {
- EventReceived = false;
- bar.BarEvent += ReceiveBarEvent;
- }
- private void ReceiveBarEvent(object sender, EventArgs args)
- {
- EventReceived = true;
- }
- }
- internal class BarStub : IBar
- {
- public event BarEventHandler BarEvent;
- //Stub method that invokes the event
- public void RaiseBarEvent()
- {
- BarEvent.Invoke(this, new EventArgs());
- }
- }
- public delegate void BarEventHandler(object sender, EventArgs args);
- public interface IBar
- {
- event BarEventHandler BarEvent;
- }
Add Comment
Please, Sign In to add comment