gpt4 book ai didi

C# ASP.NET MVC Controller 单元测试

转载 作者:行者123 更新时间:2023-11-30 20:36:36 25 4
gpt4 key购买 nike

我是单元测试的新手,我想知道我做的是否正确。

//Controller
public ActionResult Index()
{
return View("../Message/Index");
}

[TestMethod]
public void MessageViewCorrectTest()
{
var controller = new MessageController();
var result = controller.Index() as ViewResult;
Assert.AreEqual("../Message/Index", result.ViewName);
}

[TestMethod]
public void MessageViewInCorrectTest()
{
var controller = new MessageController();
var result = controller.Index() as ViewResult;
Assert.AreNotEqual("Something/Else", result.ViewName);
}

我这样做对吗,有没有更好的方法或者这样好吗?

如有任何反馈,我们将不胜感激,在此先致谢。

最佳答案

这里有一个方法可以做到。您也可以根据您的模型类型进行验证

[TestMethod]
public void TestMethod2()
{
MessageController controller = new MessageController();
ActionResult result = controller.Index(1);
Assert.IsInstanceOfType(result, typeof(ViewResult));
//Since view has been asserted as ViewResult
ViewResult viewResult = result as ViewResult;
if(viewResult != null)
{
Assert.IsInstanceOfType(viewResult.Model, typeof(YourModelType));
//Further Asserts for your model
}
}

关于C# ASP.NET MVC Controller 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com