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);


        }
相關文章
相關標籤/搜索