单元测试MVC控制器 [英] Unit Testing MVC Controllers

查看:143
本文介绍了单元测试MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC应用程序$ P $ A控制器根据几个相当简单的规则,对填充我的视图中显示表单数据。

A controller in my ASP.NET MVC application pre-populates form data displayed by my view according to a couple of fairly straight forward rules.

看起来这将是我的单元测试覆盖件好事。但我看得出来验证正确的数据被放置在窗体的唯一方法,是从什么感觉不自然的控制器中提取的逻辑。

It seems like this would be a good thing to cover in my unit testing. But the only way I could see to verify the correct data is placed in the form, would be to extract the logic from the controller in what feels like an unnatural way.

有人建议的方式来解决这个?

Can someone suggest ways to approach this?

我发现单元测试控制器的所有的例子都显得很琐碎,如验证它返回的观点预期的类型。我不知道我甚至看到了价值。

All the examples I've found of unit testing controllers seemed very trivial, such as verifying it returned the expected type of view. I'm not sure I even see the value in that.

推荐答案

您可以通过返回的对象转换为相应的类,而不是使用其基类(这是默认返回)测试

You can test by casting the returned object to the appropriate class, instead of using their base class (which is returned by default)

例如,要测试默认的的AccountController 你会这样是这样的:

For example, to test the default AccountController you'd so something like this:

var controller = new AccountController();
var result = controller.LogOn() as ViewResult;
var model = result.Model as LogOnModel;

Assert.IsTrue(model.RememberMe); // assuming you "pre-populated" enabled the checkbox

检查返回的对象充满了正确的数据似乎并没有不自然对我来说,还是你的意思是不同的?

Checking if the returned object is filled with the right data does not seem "unnatural" to me, or did you meant it differently?

这篇关于单元测试MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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