1

嗨,我对 MVC 很陌生,我正在尝试创建一个从华氏温度到摄氏温度的简单转换以及它的单元测试。提前抱歉将所有代码放在这里。

这是我的控制器代码:

public string Convert(double value,string option)
{
    string d;

    if(option=="1") {
        d = " To Celcius"+FahrenheitToCelsius(value).ToString();
    }
    else {
        d = " To Fahrenheit" + CelsiusToFahrenheit(value).ToString();
    }
    return "ConvertTo" + d;
}

public static double CelsiusToFahrenheit(double temperatureCelsius)
{
    double celsius = temperatureCelsius;
    return (celsius * 9 / 5) + 32;
}

public static double FahrenheitToCelsius (double temperatureFahrenheit)
{
    double fahrenheit = temperatureFahrenheit;
    return (fahrenheit - 32) * 5 / 9;
}

这是我的查看页面

protected void btnConvert(object sender, EventArgs e)
{
    if (DropDownList1.SelectedValue=="1"){
        double temp = TemperatureConverterController.FahrenheitToCelsius(double.Parse(TextBox1.Text));
        Literal1.Text = temp.ToString();
    }
    else{
        double temp = TemperatureConverterController.CelsiusToFahrenheit(double.Parse(TextBox1.Text));
        Literal1.Text = temp.ToString();
        Literal1.Text = temp.ToString();
    }
}

当我做这个单元测试时,我得到了一个错误:

[TestMethod]
public void ConvertReturnsAViewResultWhenInputDataIsValid()
{
    //Arrange
    var controller = new TemperatureConverterController();

    //Act
    double x = 80;
    double y = 25;
    var result = controller.Convert(x, "1") as ViewResult;
    //    here i get this error under ViewResult //

    //Assert
    Assert.IsInstanceOfType(result, typeof(ViewResult));
}

[TestMethod]
public void ConvertAsksForAViewTemplateNamedConvert()
{
    //Arrange
    var controller = new TemperatureConverterController();
    String expectedViewTemplate = "Convert";

    //Act
    double x = 80;
    double y = 25;
    var result = controller.Convert(x, "1") as ViewResult;
    ////Assert
    Assert.AreEqual<String>(expectedViewTemplate, result.ViewName);
}

错误是:

Error   Cannot convert type 'string' to 'System.Web.Mvc.ViewResult' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.
4

3 回答 3

2

问题就在这里

var result = controller.Convert(x, "1") as ViewResult;

您的 Convert 方法正在返回字符串,并且您将其转换为 ViewResult

您的转换方法应如下所示

public ActionResult Convert()
{
    //Make a Model class and pass it to View
    //...
    return View(model_class_object);
}

或者,您可以像这样制作控制器

public ActionResult Convert()
{
    ViewData["tempvalue"]=Convert(x, "1");
    //Make a Model class and pass it to View
    //...
    return View();
}

在你的视图上你可以打印它

@ViewData["tempvalue"].ToString()
于 2013-01-17T12:56:01.727 回答
0

在 MVC 中,控制器代码应返回包含模型的“ActionResult”对象。

如果您要传递给视图的数据只是一个字符串,请使用:

public ActionResult Convert()
{
    //...
    return View("your result here...");
}

您可以使用视图或测试中的“模型”属性来引用控制器返回的数据。

于 2013-01-17T12:54:07.030 回答
-1

让我们在这里倒退一分钟。

控制器

public class ConvertController : Controller
{
    public ActionResult Convert(MyConvertViewModel vm)
    {
        if (vm == null) { return View("convert", new MyConvertViewModel { ShowResult = false }); }

        if (vm.Option == 1)
        {
            vm.Result = FahrenheitToCelsius(vm.Input);
            vm.OptionName = "Fahrenheit To Celsius";
        }
        else
        {
            vm.Result = CelsiusToFahrenheit(vm.Input);
            vm.OptionName = "Celsius to Fahrenheit";
        }
        vm.ShowResult = true;

        //not needed, just for an example
        ViewData.Add("glosrob-example", "A value goes here!");

        return View("convert", vm);
    }

    private static double CelsiusToFahrenheit(double temperatureCelsius)
    {
        double celsius = temperatureCelsius;
        return (celsius * 9 / 5) + 32;
    }

    private static double FahrenheitToCelsius(double temperatureFahrenheit)
    {
        double fahrenheit = temperatureFahrenheit;
        return (fahrenheit - 32)*5/9;
    }
}

public class MyConvertViewModel
{
    public double Result { get; set; }
    public int Option { get; set; }
    public double Input { get; set; }
    public string OptionName { get; set; }
    public bool ShowResult { get; set; }
}

看法

@model MvcApplication1.Controllers.MyConvertViewModel
@{
    ViewBag.Title = "Convert";
}
<h2>Convert</h2>

@using (Html.BeginForm("convert", "convert", FormMethod.Post))
{
 <div>
     Let's convert some temperatures!
 </div>
 <div>
     @Html.LabelFor(x => x.Input, "Temp. To Convert")
     @Html.TextBoxFor(x => x.Input)
 </div>
 <div>
     @Html.LabelFor(x => x.Option, "Convert to ")
     @Html.DropDownListFor(x => x.Option, new List<SelectListItem>
     {
         new SelectListItem {Text = "Celsius", Value = "1"},
         new SelectListItem {Text = "Fahrenheit", Value = "2"}
     })
 </div>
 <div>
     <button type="submit">Convert It!</button>
 </div>
}
@if (Model.ShowResult)
{
    <p>@Model.OptionName : @Model.Input = @Model.Result</p>
}

免责声明:那里有很多快捷方式,它只是为了让您了解您应该拥有什么。

所以视图会将用户选择的数据发回给控制器动作Convert

控制器会依次返回一个 ViewResult 对象,并使用视图模型中捕获的数据进行渲染MyConvertViewModel

现在我们要对此进行测试。

所以这里有一些更重要的属性,你似乎需要加入这些属性

[TestMethod]
public void Not_A_Real_Test_But_Stuff_You_Will_Want_To_Use()
{
    //arrange
    var c = new ConvertController();

    //act
    var results = c.Convert(null) as ViewResult;

    //now results is a ViewResult or null

    var theViewModelProperty = results.Model as MyConvertViewModel;
    var exampleResult = theViewModelProperty.Result;
    var exampleInput = theViewModelProperty.Input;

    //etc

    //how about the view that was returned?
    var theViewName = results.ViewName;

    //or anything you put in the ViewData
    var theViewData = results.ViewData["glosrob-example"];

    Assert.Fail("This was not a real test!");
}

希望这能让您了解如何测试控制器方法的输出。

编辑:我不是为你写所有的测试,而是作为一个例子

[TestMethod]
public void Convert_Should_Return_A_MyConvertViewModel()
{
    //arrange
    var c = new Controller();

    //act
    var result = c.Convert(null) as ViewResult;

    //assert
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result.ViewModel, typeof(MyConvertViewModel));
}

[TestMethod]
public void Convert_Should_Return_The_Correct_View()
{
    //arrange
    var c = new Controller();

    //act
    var result = c.Convert(null) as ViewResult;

    //assert
    Assert.IsNotNull(result);
    Assert.AreEqual("convert", result.ViewName);
}
于 2013-01-17T13:30:27.830 回答