我有一个使用.NetCore创建的Windows服务应用程序。 我想为服务方法创建一些单元测试。
启动类如下
public class Startup
{
public static IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
}
需要测试的类
public class ModelConsumer : IModelConsumer
{
private readonly IProcessHandler _processHandler;
public ModelConsumer(IIProcessHandler processHandler)
{
_processHandler = processHandler;
}
public void OnMessageReceived(ModelDto model)
{
var exportFolder = Startup.Configuration["ExportFolder"];
// do actions
}
}
测试班
[TestClass]
public class ModelConsumerTests
{
[TestMethod]
public void OnMessageReceived()
{
var processHandler = new Mock<IProcessHandler>();
var modelConsumer = new ModelConsumer(processHandler.Object);
var config = InitConfiguration();
var _exportFolder = config["ExportFolder"];
modelConsumer.OnMessageReceived(new ModelDto());
// verify mock call actions
}
public static IConfiguration InitConfiguration()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
return config;
}
}
配置中缺少某些内容,因此测试可以成功运行吗?
答案 0 :(得分:0)
期望 Test 项目的appsettings.json
文件夹中有bin/
。因此,您必须将其复制到测试项目中/新建一个项目,并确保将其复制到构建版本的输出中。