- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从单元测试开始,并使用 XUnit 进行测试。
我有一个模型:
using Newtonsoft.Json;
namespace HomeAddressSearch
{
public class Properties
{
[Required]
[JsonProperty(PropertyName = "civic_number")]
public string CivicNumber { get; set; }
[JsonProperty(PropertyName = "address")]
public string Address { get; set; }
[JsonProperty(PropertyName = "postal_code")]
public string PostalCode { get; set; }
[JsonProperty(PropertyName = "city_name")]
public string CityName { get; set; }
}
}
我有一个 JSON,我从中获取如下值:
[
{
"properties": {
"civic_number": "100",
"address": "100, king street",
"postal_code": "H0H0H0",
"city_name": "Windsor"
},
"owner": {
"name": "John Doe",
"age": "40"
},
}
]
所以我想测试那个模型,为此我想到了:
我是否在正确的道路上以及如何做到这一点,这将极大地帮助和启动我做很多其他事情。
谢谢!
最佳答案
这不是您需要进行单元测试的东西,而是利用 Newtonsoft 的 JSON 验证。
// Generate a JSON schema from your object.
var schemaGenerator = new JSchemaGenerator();
var schema = schemaGenerator.Generate(typeof(HomeAddressSearch.Properties));
// Parse the JSON passed in, then validate it against the schema before proceeding.
List<ValidationErrors> validationErrors;
JObject addressToValidate = JObject.Parse(jsonStringToValidate);
bool isValid = addressToValidate.IsValid(schema, out validationErrors);
如果您想详细说明对调用者的响应,您可以从那里遍历验证错误。
单元测试适用于断言静态代码行为,因此如果您的 JSON 模式指定规则,则单元测试所做的断言是:
** 编辑 ** 详细说明使用验证,然后执行验证的单元测试:
假设我们有一个 API 接受 JSON 数据作为字符串而不是类:(我们应该能够使用 model.IsValid())
public class AddressController : ApiController
{
private readonly IJsonEntityValidator<HomeAddressSearch.Properties> _validator = null;
public AddressController(IJsonEntityValidator validator)
{
_validator = validator;
}
public ActionResult Search(string jsonModel)
{
if(string.IsNullOrEmpty(jsonModel))
// handle response for missing model.
var result = _validator.Validate<HomeAddressSearch.Properties>(jsonModel);
if (!result.IsValid)
// handle validation failure for the model.
}
}
public class JSonEntityValidator<T> : IJsonEntityValidator<T> where T: class
{
IJsonEntityValidator<T>.Validate(string jsonModel)
{
// Generate a JSON schema from your object.
var schemaGenerator = new JSchemaGenerator();
var schema = schemaGenerator.Generate(typeof(T));
// Parse the JSON passed in, then validate it against the schema before proceeding.
List<ValidationErrors> validationErrors;
JObject model = JObject.Parse(jsonModel);
bool isValid = model.IsValid(schema, out validationErrors);
return new JsonValidateResult
{
IsValid = isValid,
ValidationErrors = validationErrors
};
}
}
单元测试将针对 Controller ,断言它使用验证器来确保 JSON 数据有效:
[Test]
public void EnsureHomeAddressSearchValidatesProvidedJson_InvalidJSONScenario()
{
string testJson = buildInvalidJson(); // the value here doesn't matter beyond being recognized by our mock as being passed to the validation.
var mockValidator = new Mock<IJsonEntityValidator<HomeAddressSearch.Properties>>();
mockValidator.Setup(x => x.Validate(testJson)
.Returns(new JsonValidationResult { IsValid = false, ValidationErrors = new ValidationError[] { /* populate a set of validation errors. */ }.ToList()});
var testController = new AddressController(mockValidator.Object);
var result = testController.Search(testJson);
// Can assess the result from the controller based on the scenario validation errors returned....
// Validate that our controller called the validator.
mockValidator.Verify(x => x.Validate(testJson), Times.Once);
}
此测试完成的是断言我们的 Controller 将调用验证逻辑来评估我们提供的 JSON。如果有人修改 Controller 并删除对 Validate 的调用,测试将失败。
您不需要为这样的测试编写 JSON 对象,“fred”就可以了,因为它只是供模拟识别的占位符。此场景中的模拟配置为:“我希望以特定的值(value)被调用。[fred]”“当我得到那个值时,我会说它无效,并且我会包含一组特定的验证错误。”从那里您可以断言 Controller 的结果响应以查看它是否反射(reflect)了验证错误。我们还要求最后的 Mock 验证它是用特定值调用的。
现在,如果您还想强制/断言对架构的更改,那么您可以针对验证器本身编写测试。例如检测有人删除或更改模型上的属性。
[Test]
EnsureHomeAddressValidatorExpectsCivicNumberIsRequired()
{
var testJson = generateJsonMissingCivicNumber();
IJsonEntityValidator<HomeAddressSearch.Properties> testValidator = new JsonEntityValidator<HomeAddressSearch.Properties>();
var result = testValidator.Validate(testJson);
Assert.IsFalse(result.IsValid);
// Assert result.ValidationErrors....
}
关于C# 单元测试 Newtonsoft JSON 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52415325/
我在谷歌上花了很长时间,所以如果这是一个简单的修复请原谅我,但我找不到任何与 C# 中这个特定问题的修复相关的内容。 当尝试使用以下代码时,出现此错误: string obj = JsonConver
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 去年关闭。 Improve this
我正在尝试重新创建这个 json: { "request": { " TestRequest": { "OrderID": {
我正在测试我的 Web API。模拟数据我有这个: var objs = ((JArray)JsonConvert.DeserializeObject("{ \"PrintId\":10,\"Head
目前正在尝试使用 fixer.io API 在 C# 中创建货币转换。 我在从 Twitter API 解析 JSON 时使用了与下面类似的方法,并且没有任何问题,我不完全确定这里发生了什么。 API
我正在尝试建立 Mike Jansen 的 JIRA REST Client ,我正在尝试提取 JIRA 版本信息。我是 JSON 的新手,所以我不确定这只是格式问题还是什么。 调试时,我有以下标记:
我正在尝试使用 将对象动态序列化到即时窗口中 Newtonsoft.Json.JsonConvert.SerializeObject(myObj); 但是我得到以下错误 The type 'Newto
我无法在 Visual Studio 2013 中构建解决方案。 这发生在我将我的 JSON.NET 包更新到 6.0.1 之后。在此之前,它就像一个魅力。 有什么想法吗? PS:这可能是关于 OWI
当有如下代码时 var TermSource = token.Value("annotations") .Values("Term Source") .FirstOrDefault
我需要将选中的复选框代码从 JavaScript 传递给 C#。我能够通过 JSON 发送代码。我的 JSON 值以 JArray 的形式出现。我在标题中得到了异常(exception)。 JSON:
注意:解决重定向问题后,我遇到了另一个问题,即出现错误“无法将 Newtonsoft.Json.Linq.JArray 转换为 Newtonsoft.Json.Linq.JToken”。因此,在我的回
我有以下简单的 POCO: public class ApiKey { public ApiKey(string key, string owner, List claims = nu
我查过这个问题,但我没有看到太多答案,显然没有一个有帮助,否则我不会问。我是 .NET 新手。 我的本地环境是Win7,Microsoft Virtual Web Developer 2010 Exp
好的-我已经将这个问题打了几个小时。是时候寻求帮助了。 我刚刚将Web应用程序项目升级到ASP.NET MVC 4 RC和新的WebApi。 我的Web api方法现在返回EMPTY json“{}”
我想忽略类中的某些属性,但出于多种原因我想保留类 POCO。因此我不想引入对 Json.NET 的依赖,也不想使用 JsonIgnoreAttribute。 有没有办法自定义契约(Contract)解
我正在尝试修复我编写的 WinForms 程序中的错误;我正在解析一个 JSON 字符串,然后将一些结果放入各种变量中。 有时,JSON 的特定元素不存在(出于真正的原因),因此我尝试使用以下代码来处
我只是尝试使用 C# 中的 Newtonsoft JSON 库将文件中的一些 JSON 反序列化为对象列表。以下是 MeetingFile.txt 文件的内容: [ { "People":
这是一个非常奇怪的错误发生。我有这些对象: public class Mobile_SettingModels { public string Token { get; set; }
我粘贴了 http://www.codeproject.com/Tips/789481/Bridging-the-Gap-between-Linqpad-and-Visual-Studio 中的代码进
这个问题在这里已经有了答案: Can I optionally turn off the JsonIgnore attribute at runtime? (3 个答案) 关闭 4 年前。 我目前正
我是一名优秀的程序员,十分优秀!