为什么这个asp.net mvc的单元测试失败? [英] Why does this asp.net mvc unit test fail?

查看:94
本文介绍了为什么这个asp.net mvc的单元测试失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编辑并简化了这个问题很多。

I have edited and simplified this question a lot.

如果我有我的HomeController此方法:

If I have this method on my HomeController:

    public ActionResult Strangeness( int id )
    {
        StrangenessClass strangeness = null;

        if( id == 1 )
        {
            strangeness = new StrangenessClass() { Name="Strangeness", Desc="Really weird behavior" };
        }

        return View( strangeness );
    }

和这个类:

public class StrangenessClass
{
    public string Name { get; set; }
    public string Desc { get; set; }
}

为什么这个单元测试失败?

Why does this unit test fail?

    [TestMethod]
    public void Strangeness()
    {
        HomeController controller = new HomeController();

        ViewResult result = controller.Strangeness( 1 ) as ViewResult;
        var model = result.ViewData.Model;
        result = controller.Strangeness( 2 ) as ViewResult;
        model = result.ViewData.Model;

        Assert.IsNull( model );
    }

据我了解,通常情况下,我将有一个测试,测试空状态,另一个测试一个良好的状态,但我遇到了这个问题,同时测试我删除控制器。在删除测试中,我通常会取记录,删除记录,然后尝试再次获取它。它应该是空的我第二次去取,但事实并非如此。所以,我煮问题下来,如上所述。

I understand that normally, I would have one test to test the null condition and another to test a good condition, but I ran into this problem while testing my delete controller. On a delete test, I would normally fetch the record, delete the record, and then attempt to fetch it again. It should be null the second time I fetch it, but it wasn't. So, I boiled the problem down as described above.

如果这不是测试删除的正确方法,你会怎么做呢?难道你需要确保该纪录是实际删除?

If this is not the proper way to test deletes, how would you do it? Don't you need to make sure that the record was actually deleted?

推荐答案

您不应该再用控制器来处理多个请求,这是你在做什么,在这里。

You should not reuse a controller to handle multiple requests, which is exactly what you are doing here.

无论如何,如果你查看​​源$ C ​​$ C为MVC 你会发现这种现象的原因:

Anyway, if you check the source code for MVC you'll find the reason for this behavior:

protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
    if (model != null)
    {
        base.ViewData.Model = model;
    }
    return new ViewResult { ViewName = viewName, MasterName = masterName, ViewData = base.ViewData, TempData = base.TempData };
}

如果模型为空,这不是分配给ViewData.Model属性。
如果你想正确的行为,为你的第二个电话一个新的控制器,以 HomeController.Strangeness

If the model is null, it's not assigned to the ViewData.Model property. If you want the correct behaviour, create a new controller for your second call to HomeController.Strangeness.

这篇关于为什么这个asp.net mvc的单元测试失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆