首页新闻找找看学习计划

asp .net core 使用TestServer 测试,view 一大堆未引用

1
悬赏园豆:60 [已解决问题] 解决于 2017-09-07 19:17

按照官方文档

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing

写TestServer 基本没改什么,项目也是新建的

写了IClassFixture

UseContentRoot路径也正确

使用_httpClient 调用 返回视图

 

 1 /// <summary>
 2     /// A test fixture which hosts the target project (project we wish to test) in an in-memory server.
 3     /// </summary>
 4     /// <typeparam name="TStartup">Target project's startup type</typeparam>
 5     public class TestFixture<TStartup> : IDisposable
 6     {
 7         private const string SolutionName = "Core2.0.sln";
 8         private readonly TestServer _server;
 9 
10         public TestFixture()
11             : this(Path.Combine("Front"))
12         {
13         }
14 
15         protected TestFixture(string solutionRelativeTargetProjectParentDir)
16         {
17             var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
18             var contentRoot = GetProjectPath(solutionRelativeTargetProjectParentDir, startupAssembly);
19 
20             var builder = //WebHost.CreateDefaultBuilder()
21                 new WebHostBuilder()
22                 .UseContentRoot(contentRoot)
23                 .ConfigureServices(InitializeServices)
24                 .UseEnvironment("Development")
25                 .ConfigureAppConfiguration(config=>config.AddJsonFile("appsettings.json", true, true).AddJsonFile("appsettings.Development.json", true, true))
26                 .UseStartup(typeof(TStartup));
27 
28             _server = new TestServer(builder);
29 
30             Client = _server.CreateClient();
31             Client.BaseAddress = new Uri("http://localhost");
32         }
33 
34         public HttpClient Client { get; }
35 
36         public void Dispose()
37         {
38             Client.Dispose();
39             _server.Dispose();
40         }
41 
42         protected virtual void InitializeServices(IServiceCollection services)
43         {
44             var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
45 
46             // Inject a custom application part manager. Overrides AddMvcCore() because that uses TryAdd().
47             var manager = new ApplicationPartManager();
48             manager.ApplicationParts.Add(new AssemblyPart(startupAssembly));
49 
50             manager.FeatureProviders.Add(new ControllerFeatureProvider());
51             manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
52 
53             services.AddSingleton(manager);
54         }
55 
56         /// <summary>
57         /// Gets the full path to the target project path that we wish to test
58         /// </summary>
59         /// <param name="solutionRelativePath">
60         /// The parent directory of the target project.
61         /// e.g. src, samples, test, or test/Websites
62         /// </param>
63         /// <param name="startupAssembly">The target project's assembly.</param>
64         /// <returns>The full path to the target project.</returns>
65         private static string GetProjectPath(string solutionRelativePath, Assembly startupAssembly)
66         {
67             // Get name of the target project which we want to test
68             var projectName = startupAssembly.GetName().Name;
69 
70             // Get currently executing test project path
71             var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
72 
73             // Find the folder which contains the solution file. We then use this information to find the target
74             // project which we want to test.
75             var directoryInfo = new DirectoryInfo(applicationBasePath);
76             do
77             {
78                 var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, SolutionName));
79                 if (solutionFileInfo.Exists)
80                 {
81                     return Path.GetFullPath(Path.Combine(directoryInfo.FullName, solutionRelativePath, projectName));
82                 }
83 
84                 directoryInfo = directoryInfo.Parent;
85             }
86             while (directoryInfo.Parent != null);
87 
88             throw new Exception($"Solution root could not be located using application root {applicationBasePath}.");
89         }
90     }

 

 1 public class HomeControllerTest : IClassFixture<TestFixture<Startup>>
 2     {
 3         private readonly HttpClient _httpClient;
 4 
 5         public HomeControllerTest(TestFixture<Startup> fixture)
 6         {
 7             _httpClient = fixture.Client;
 8         }
 9 
10         [Fact]
11         public async Task IndexTestAsync()
12         {
13             var req = new HttpRequestMessage(HttpMethod.Get, "/");
14 
15             string responseString = null;
16 
17             var rep = await _httpClient.SendAsync(req);
18             using (rep)
19             {
20                 responseString = await rep.Content.ReadAsStringAsync();
21                 Console.Write(responseString);
22             }
23 
24             // Assert
25             Assert.True(rep.IsSuccessStatusCode);
26         }
27 
28     }

 

一大堆未引用

视图原因

直接返回字符串或json 没有任何问题

 

 

 

responseString内容

https://wjvstoo.win/html/test.html

 

Jadyn.Wong的主页 Jadyn.Wong | 初学一级 | 园豆:60
提问于:2017-09-04 17:47
< >
分享
最佳答案
0

你的项目用 dotnet run 跑的起来吗?应该跑不起来吧。你的Web层中 csproj 文件是怎么样的?

收获园豆:60
BUTTERAPPLE | 老鸟四级 |园豆:2918 | 2017-09-04 17:55

可以的 正常运行

Jadyn.Wong | 园豆:60 (初学一级) | 2017-09-04 19:05

csproj就是 core2.0新建的mvc项目,没有任何修改

Jadyn.Wong | 园豆:60 (初学一级) | 2017-09-04 19:06

@WJvsToo: 你好,在吗? 我今天按照你的那样新建试了一下,确实出现了你的那样的错误。然后发现了一个解决办法,我在本地已经可以正常运行了,
你修改一下 test 项目下的 .csproj 文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <PreserveCompilationContext>true</PreserveCompilationContext>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20170810-02" />
    <PackageReference Include="xunit" Version="2.3.0-beta5-build3769" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.3.0-beta5-build3769" />
    <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.0.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\MiddlewareDemo\MiddlewareDemo.csproj" />
  </ItemGroup>

  <Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
    <ItemGroup>
      <DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
    </ItemGroup>

    <Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
  </Target>

</Project>

上面那个是我的,你看着修改就可以了

然后添加一个 xunit.runner.json 文件

{
  "shadowCopy": false
}

然后你再运行一下,应该就正常没有问题了。
参考链接 :Integration tests with ASP.NET Core causes missing references from Razor files

BUTTERAPPLE | 园豆:2918 (老鸟四级) | 2017-09-07 13:32

BUTTERAPPLE | 园豆:2918 (老鸟四级) | 2017-09-07 13:33

@BUTTERAPPLE: 嗯嗯,谢谢

Jadyn.Wong | 园豆:60 (初学一级) | 2017-09-07 19:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册