【发布时间】:2018-05-26 20:40:03
【问题描述】:
我正在尝试构建一个将驻留在其自己的 DLL 中的基本夹具,以便许多测试项目都可以使用它。
我在设置内容根目录时遇到问题
.UseContentRoot(projectPath)
我下面的内容有效,但我正在对solutionName 进行硬编码。
问题
如何在不进行硬编码的情况下获取 contentRoot?
我可以在我的 baseFixture 中注入任何东西吗? IHostingEnvironment 或 solutionName?
public class BaseFixture<TStartup> : IDisposable where TStartup : class
{
public BaseFixture()
{
var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
var projectPath = GetProjectPath(startupAssembly);
var host = new WebHostBuilder()
.UseContentRoot(projectPath)
.UseStartup(typeof(TStartup));
Server = new TestServer(host);
Client = Server.CreateClient();
}
private string GetProjectPath(Assembly startupAssembly)
{
//Get name of the target project which we want to test
var projectName = startupAssembly.GetName().Name;
//Get currently executing test project path
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
//Find the folder which contains the solution file. We then use this information to find the
//target project which we want to test
DirectoryInfo directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, "HardCodedSolutionName.sln"));
if (solutionFileInfo.Exists)
{
return Path.GetFullPath(Path.Combine(directoryInfo.FullName, projectName));
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be located using application root {applicationBasePath}");
}
public TestServer Server { get; set; }
public HttpClient Client { get; }
public void Dispose()
{
Server.Dispose();
Client.Dispose();
}
}
【问题讨论】:
-
为什么不搜索
*.sln文件来获取解决方案名称?
标签: c# asp.net-core asp.net-core-webapi xunit