使用ContentResult类型对C#进行单元测试

时间:2013-07-01 16:53:26

标签: c# unit-testing asp.net-mvc-4

我在mvc.net c#

中有一个控制器的动作
public ContentResult GetVariableMapKml(string variableId, string sitesIds, string beginDate, string endDate, int limit)
    {
        Object resultData = null;
        // Prepare specific Json configuration
        var serializer = new JavaScriptSerializer();

        if (variableId != null && variableId != "")
        {
           ...
            if (valuesList != null)
            {
                resultData = new
                {
                    Values = valuesList,
                    Units = varUnits
                };
            }
            else
            {
               resultData = new
               {
                   Error = "Error at GetVariableMapKml() method: Null params"
               };
            }

        }

        var result = new ContentResult
        {
            Content = serializer.Serialize(resultData),
            ContentType = "application/json"
        };

        return result;
    }

我在c中进行单元测试,我需要访问ContentResult的结果,检查变量Error是否为空。

[TestMethod]
    public void GetVariableMapKmlWrongParams()
    {
        FieldDataController controller = new FieldDataController();
        controller.ControllerContext =  
        TestUtils.CreateMockSessionControllerContext().Object as ControllerContext;

        //param null
        ContentResult result = controller.GetVariableMapKml(null, null, "05/05/2001", 
                                                            "02/10/2012", 100);
        Assert.IsNotNull("Error");
    }

如何访问错误内容并检查此内容是否为空?谢谢。

1 个答案:

答案 0 :(得分:2)

你可以这样做

    [TestMethod]
    public void GetVariableMapKmlWrongParams()
    {
        FieldDataController controller = new FieldDataController();
        controller.ControllerContext =
        TestUtils.CreateMockSessionControllerContext().Object as ControllerContext;

        //param null
        ContentResult result = controller.GetVariableMapKml(null, null, "05/05/2001",
                                                            "02/10/2012", 100);

        var returnedObject = (Dictionary<string, object>)(new JavaScriptSerializer()).DeserializeObject(result.Content);

        Assert.IsTrue(returnedObject.ContainsKey("Error"));

    }

您可以测试字典对象是否存在键及其值