我有一个在运行时通过JSON反序列化创建的类:
public class Server
{
protected IDataRepository DataRepository;
public string Name { get; }
protected Server(string Name, IDataRepository DataRepository)
{
this.Name = HostName;
this.DataRepository= DataRepository;
}
}
反序列化是在特定的类中完成的:
public class SettingsServersRepository : IServersRepository
{
public IEnumerable<Server> Servers {get;}
public SettingsServersRepository(string jsonSettings)
{
Servers = JsonConvert.DeserializeObject<IEnumerable<Server>>(jsonSettings);
}
}
在反序列化过程中,使用构造函数注入将IDataRepository
注入到Server
中。
它在运行时工作正常。
但是,当我想对课程进行单元测试时:
public void CreateFromBasicJSON()
{
//Arrange
string testJSON = "[{'Name': 'foo'},{'Name': 'bar'}]";
//Act
IServersRepository serverRepoFromJson = new SettingsServersRepository(testJSON);
//Assert
Assert.IsTrue(serverRepoFromJson.Servers.ElementAt(0).Name ==
"foo");
}
缺少依赖项,并且在NullReferenceError
构造函数中抛出了Server
。
我首先想到的是在单元测试中使用依赖项注入容器,以确保注入了依赖项。
感觉不像the right thing to do™
,但是缺少仅为此目的构建自定义JsonConverter并将IServersRepository
放在堆栈中的想法,我没有更好的主意。
问题:
可以在单元测试中使用依赖项注入容器吗?如果没有,我该如何改善?