snowmom475
snowmom475

Reputation: 977

nunit test case- Verify edited note is correct

In the example below, I'm attempting to test that the notes text is changed. Is the Assert.AreEqual(note.Text, text); correct?

    [TestMethod()]
    public void CreateNoteTest_Pass()
    {
        HomeController target = new HomeController(); // TODO: Initialize to an appropriate value
        var note = new NotePM();

        string text = "This is my test note" + DateTime.Now;
        note.Text = text;
        int id = note.NoteId;
        note.CreatedByUserName = Membership.GetUser("danielle").UserName;

        ActionResult actual;
        actual = target.Create(note);
        Assert.AreNotEqual(id, note.NoteId);
        Assert.IsInstanceOfType(actual, typeof(RedirectToRouteResult));
        Assert.AreEqual(note.Text, text);

    }

Upvotes: 1

Views: 47

Answers (1)

StuartLC
StuartLC

Reputation: 107267

Here's one take on this:

[TestMethod()]
public void EnsureCreateNoteChangesNoteText()
{
    string text = "This is my test note" + DateTime.Now;
    var note = new NotePM()
    {
        Text = text;
        CreatedByUserName = "danielle";
    };

    int id = note.NoteId;

    ActionResult actual;
    HomeController target = new HomeController();
    actual = target.Create(note);
    Assert.AreNotEqual(id, note.NoteId, "note.NoteID must be assigned by the controller");
    Assert.IsInstanceOfType(actual, typeof(RedirectToRouteResult));
    Assert.AreNotEqual(text, note.Text, "note.Text must be changed by the controller");
}
  • Assert.AreNotEqual() is used to check for inequality (and there is a string overload which does a value comparison)
  • With the asserts which take 2 values, these should be Assert.xxx(Expected, Actual) otherwise the failure message is inverted.
  • Unit tests should isolate the system under test as far as possible (HomeController in this example). If HomeController is dependent on asp.net Membership ideally, you should inject this to the controller in the constructor to ensure it can be mocked. This way you can ensure that the unit test runs without the need to prep database data, setup connections from the Unit Test runner, etc.

Upvotes: 1

Related Questions