集成测试
集成测试可在包含应用支持基础结构(如数据库、文件系统和网络)的级别上确保应用组件功能正常
单元测试关注是的软件最小可执行单元是否能够正常执行,但软件是由一个个最小执行单元组成的集合体,单元与单元之间存在着种种依赖或联系,所以在开发时仅仅确保最小单元的正确往往不够,为了保证软件能够正确运行,单元与单元之间的集成测试是非常必要。
与单元测试相比,集成测试可在更广泛的级别上评估应用的组件。 单元测试用于测试独立软件组件,如单独的类方法。 集成测试确认两个或更多应用组件一起工作以生成预期结果,可能包括完整处理请求所需的每个组件。
TestServer
使用TestServer测试API接口
protected TestServer CreateSingleTestServer(){if (testServer == null){lock (singleton_Lock){if (testServer == null){string path = Assembly.GetAssembly(typeof(TestBase)).Location;IWebHostBuilder hostBuilder =new WebHostBuilder().UseContentRoot(Path.GetDirectoryName(path)).ConfigureAppConfiguration(cb =>{cb.AddJsonFile("appsettings.test.json", true, true);}).UseEnvironment("Development").UseStartup<TestStartup>();testServer = new TestServer(hostBuilder);}}}return testServer;}public class TestStartup : Startup{public TestStartup(IConfiguration configuration,IHostingEnvironment env) : base(configuration, env){if debugstring connectionString =Configuration.GetSection("Database:ConnectString").Value;testDbContext =new ApplicationDbContext(new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(connectionString).Options);endif}}}
[TestClass][TestCategory("integration")]public class ApiTest : TestBase{private HttpClient client;[TestInitialize]public void Init(){client = testServer.CreateClient();}[TestCleanup]public void Cleanup(){client.Dispose();}[TestMethod]public async Task GetAsync(){var response =await client.GetAsync($"/api/values");Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);}}
参考:
