2

我在 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");
    }

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

4

1 回答 1

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"));

    }

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

于 2013-07-02T07:46:33.690 回答