gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:54 26 4
gpt4 key购买 nike

我在 mvc.net c# 中有 Controller 的这个 Action

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 是否为 null。

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

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

最佳答案

你可以这样做

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

}

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

关于c# - 使用 ContentResult 类型对 C# 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409715/

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