I’m trying to write a unit test for a sample project that uses the MVP architecture.
When I run the test, I have the following error message:
UnitTests.Tests.testCopy:
Expected: “Testing …”
But was: null
I post below the snippets I did:
namespace Copy
{
public interface IView
{
string Copy { get; set; }
string Original { get; }
event EventHandler Changed;
}
public class Presenter
{
private IView view;
public Presenter(IView view)
{
this.view = view;
this.view.Changed += new EventHandler(OnChanged);
}
public void OnChanged(object sender, EventArgs e)
{
view.Copy = view.Original;
}
}
public partial class Form1 : Form, IView
{
private Presenter presenter;
public Form1()
{
InitializeComponent();
presenter = new Presenter(thisIView);
this.t_originalviewMock.TextChanged += OnChanged;
}
public string Original
{
get { return t_originalMockInstance).Text; }
}
public string Copy
{
get { return t_copy.Text; }
set { t_copy.Text = value;}
}
private void OnChanged(object sender, EventArgs e)
{
if (Changed != null)
Changed(sender, e);
}
public event EventHandler Changed;
}
}
Unit test code:
namespace UnitTests
{
[TestFixture]
public class Tests
{
private DynamicMock viewMock;
private Presenter presenter;
[SetUp]
public void setup()
{
viewMock = new DynamicMock(typeof(IView));
presenter = new Presenter((IView)viewMock.MockInstance);
}
[Test]
public void testCopy()
{
viewMock.ExpectAndReturn("get_Original", "Testing ...");
viewMock.Expect("get_Cpoy");
Assert.AreEqual("Testing ...",
((IView)viewMock.MockInstance).Copy);
}
}
}
Thank you for your help.
“I’m trying to test that a change in Original textBox, leads to a change in Copy textBox.”
Here’s how you should set up your test then:
Changedevent"Testing ..."upon call toget_Originalproperty getterCopysetter with"Testing ..."valueI’m not sure whether raising events is possible with NUnit.Mocks. Judging by fairly tiny API, I’d say no. Yet you can go around this problem by invoking event handler directly (since it’s public anyways):
You can see that this test indeed works by simply changing
set_Copyexpected value to something else than"Testing ..."– it will fail with appropriate message.Mocking frameworks sidenote
Any reason you’re using NUnit.Mocks instead of more serious mocking framework? Give FakeItEasy, Moq or RhinoMocks a look.
This is how your test could look like if you’d used FakeItEasy instead:
Note that problems like typing
Cpoyinstead ofCopyimmediately go away. Not to mention you won’t have to make your event handlers exposed in public API.