当写完C#代码,需要对某个方法进行测试。
创建一个XXXTests.cs文件之后,发现需要注入某个服务怎么办?
再创建一个StartupBase.cs文件:
public abstract class StartupBase
{public IConfiguration Configuration { get; }public IServiceCollection Services { get; }public IServiceProvider ScopeProvider { get; }public StartupBase(){var configurationRoot = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", false).Build();Configuration = configurationRoot;Services = new ServiceCollection();ScopeProvider = Services.BuildServiceProvider();}
}
然后把原先需要使用的appsetting.json弄进来。
如果没有,自己创建一个:
{"Env": "开发环境","Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning"}},"AllowedHosts": "*","ConnectionStrings": {"SQLConnection": ""},"CustomInfo":{}
}
记得属性改一下:
然后在自己创建的Test类中,继承StartupBase,如下:
[TestClass()]
public class SFOpenClientTests : StartupBase
{[TestMethod()]public void LogisticsTest(){var services = base.Services;var configure = base.Configuration;var scopeProvider = base.ScopeProvider;//你的逻辑代码}
}
这样就能拿到Services、Configuration、ScopeProvider。
想用哪个用哪个,没有的就到StartupBase里面注入就行。
目录结构参考如下:
然后就可以快乐地【调试测试】