简体   繁体   English

Mocking Newtonsoft.Json 单元测试时

[英]Mocking Newtonsoft.Json When Unit Testing

I'm currently testing a class that reads an embedded json file, deserialises and loads it into my DI container.我目前正在测试一个 class,它读取一个嵌入的 json 文件,反序列化并将其加载到我的 DI 容器中。 Here is a tl;dr of the code, omitting error handling:这是代码的 tl;dr,省略了错误处理:

private readonly IAssemblyManager _assemblyManager;
private readonly IContainerRegistry _containerRegistry

public void Load(string resourceName)
{
    string json = _assemblyManager.LoadResource(resourceName);

    IConfiguration config = JsonConvert.DeserializeObject<Configuration>(json);

    _containerRegistry.RegisterInstance<IConfiguration>(config);
}

I'm using NUnit and Moq to test and I'm fairly new to the testing game.我正在使用 NUnit 和 Moq 进行测试,我对测试游戏还很陌生。 I want to know the best approach to testing the JsonConvert method, I've had to write wrappers for some of my tests but would be absolutely devastated if I had to do it here.我想知道测试JsonConvert方法的最佳方法,我不得不为我的一些测试编写包装器,但如果我必须在这里这样做,那将是绝对崩溃的。 This is the most downloaded NuGet package, surely people have come across this issue and have a decent solution.这是下载次数最多的 NuGet package,肯定有人遇到过这个问题并且有一个不错的解决方案。 I've used System.IO.Abstractions to allow me to test my file access code, I would have expected there would be something similar for Newtonsoft.Json .我已经使用System.IO.Abstractions来测试我的文件访问代码,我原以为Newtonsoft.Json会有类似的东西。

Other potential workarounds could be to have my assembly manager doing the deserialisation:其他可能的解决方法可能是让我的装配经理进行反序列化:

public interface IAssemblyManager
{
    T LoadResource<T>(string resourceName);
}

But for my application I want to use the IAssemblyManager to load sql & json, I don't really want it being responsible for deserialising anything.但是对于我的应用程序,我想使用IAssemblyManager加载 sql 和 json,我真的不希望它负责反序列化任何内容。 And I've also just moved my problem from one class to another.而且我也刚刚将我的问题从一个 class 转移到另一个。

There is no official dependency injection package for Newtonsoft.JSON. Newtonsoft.JSON没有官方依赖注入package。 To test your code, there is no way around creating wrappers, unless you find a mocking framework that mocks static methods.要测试您的代码,没有办法绕过创建包装器,除非您找到一个模拟 static 方法的 mocking 框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM