dotnetcore 单元测试

   dotnetcore的单元测试目前支持的比较好的是xunit,首先经过nuget添加组件dotnet-test-xunit 和 xunit。若是有依赖注入可在构造方法中,至关于Nunit中的[Setup]。例如:web

   

 1  public class BaseRepository
 2     {
 3         public BaseRepository()
 4         {
 5             
 6             var builder = new ConfigurationBuilder()
 7                .SetBasePath(AppContext.BaseDirectory)
 8                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
 9                .AddEnvironmentVariables();
10             var configuration = builder.Build();
11             var containerBuilder = new ContainerBuilder();
12             containerBuilder.RegisterInstance<IConfigurationRoot>(configuration).SingleInstance();
13             var container = containerBuilder.Build();
14             var sl = new AutofacServiceLocator(container);
15 
16             ServiceLocator.SetLocatorProvider(() => sl);
17             containerBuilder.RegisterModule<AutofacModule>();
18 
19             var workEngin = new WebApiCoreWorkEngine(container);
20             workEngin.Initialize();
21         }
22     }

 编译后,回出如今vs的测试资源管理器中。json

关于两个实体的值的比较,可经过引入“FluentAssertions” 解决,可方便的对实体和集合值的对比。api

 若是须要对webapi进行单元测试,那么需引入“MyTested.AspNetCore.Mvc.Universe”。在测试项目中添加继承webapi中startup的类TestStartup,须要注意的是当前项目依赖必须是:app

"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
}。ide

注意加"type": "platform"。单元测试

在TestStartup中完成测试环境的依赖注入,测试

 1  public class TestStartup:Startup
 2     {
 3         
 4         public TestStartup(IHostingEnvironment env) : base(env)
 5         {
 6             
 7         }
 8 
 9         public IServiceProvider ConfigureTestServices(IServiceCollection services)
10         {
11             var types = Typefinder.GetTypeEndWith("Repository", "WebApiCore.Repository");
12             foreach (var type in types)
13             {
14                 var interfaces = type.GetInterfaces().Where(d => !d.IsConstructedGenericType).ToList();
15                 services.AddSingleton(interfaces[0], type);
16             }
17             types = Typefinder.GetTypeEndWith("Application", "WebApiCore.Application");
18             foreach (var type in types)
19             {
20                 services.AddSingleton(type);
21 
22             }
23             
24             return base.ConfigureServices(services);
25 
26         }
27     }

 

   而后能够对具体接口的测试,如ui

 

        [Fact]
        public void GetValues()
        {
            MyMvc.Controller<ShowController>()
                .Calling(d => d.HelloAsync())
                .ShouldReturn()
                .ResultOfType<OutputWithData<string>>().Passing(d=>d.ResultStatus==1);


        }
相关文章
相关标签/搜索