好吧伙计们我是MVC的新手,我正在尝试从教程中学习,我完全按照说法做了但是它让我失望
测试方法TestProject1.UnitTest1.DisplayCustomer引发异常: System.NullReferenceException:未将对象引用设置为对象的实例。 当我尝试运行单元测试时
我正在按照此处的http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7
进行教程以下是我的档案:
DisplayCustomer View
Customer ID is : <%= Model.Id %>
Customer ID is : <%= Model.CustomerCode %>
<% if (Model.Amount >100) {%>
This is a Previlaged Customer
<%} else { %>
This is a Normal Customer
<% } %>
填写客户视图:
<form action="DisplayCustomer" method = "post">
Customer ID : <input type="text" name="CustomerId" /></br>
Customer Code : <input type="text" name="CustomerCode" /></br>
Customer Amount : <input type="text" name="CustomerAmount" /></br>
<input type="submit" value="Click Here"/></br>
</form>
客户模式:
public class Customer
{
public int Id { set; get; }
public string CustomerCode { set; get; }
public double Amount { set; get; }
}
CustomerController
public class CustomerController : Controller
{
//
// GET: /Customer/
public ActionResult Index()
{
return View();
}
public ActionResult FillCustomer()
{
return View();
}
public ActionResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 10;
objCustomer.CustomerCode = "Sparkz";
objCustomer.Amount = 10.55;
var myview = View(objCustomer);
return myview;
}
}
我的单元测试文件(UnitTest1.cs): 在这里,我尝试了注释的代码和我在下面编写的代码,但都没有工作。 它始终在var customerViewViewResult / varresult
中获取null[TestClass]
public class UnitTest1
{
[TestMethod]
public void DisplayCustomer()
{
//CustomerController obj = new CustomerController();
//var varresult = obj.DisplayCustomer() as ViewResult;
//Assert.AreEqual("DisplayCustomer", varresult.ViewName);
CustomerController controller = new CustomerController();
var customer = new Customer();
var customerViewActionResult = controller.DisplayCustomer();
var customerViewViewResult = customerViewActionResult as ViewResult;
Assert.AreEqual("DisplayCustomer", customerViewViewResult.ViewName);
}
}
答案 0 :(得分:1)
我正在按照这里的教程
在本教程中,DisplayCustomer
的返回类型为ViewResult
,而不是ActionResult
// As stated in the tutorial
public ViewResult DisplayCustomer()
{
...
}