nunit测试用例 - 验证编辑过的注释是否正确

时间:2014-04-10 05:32:45

标签: unit-testing nunit

在下面的示例中,我试图测试注释文本是否已更改。是Assert.AreEqual(note.Text,text);正确的吗?

    [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);

    }

1 个答案:

答案 0 :(得分:1)

以下是对此的看法:

[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()用于检查不等式(并且存在一个字符串重载,用于进行值比较)
  • 对于带有2个值的断言,这些值应为Assert.xxx(Expected, Actual),否则失败消息将被反转。
  • 单元测试应尽可能隔离被测系统(本例中为HomeController)。如果HomeController理想地依赖于asp.net Membership,则应将其注入构造函数中的控制器以确保它可以被模拟。这样,您可以确保单元测试运行,而无需准备数据库数据,从单元测试运行器设置连接等。