Eli*_*eth 10 c# asp.net-web-api owin
http配置通常在启动类中设置,该类绑定到Create方法.
但是,如果我想要的东西,以启动一个owin服务器一次对于所有的测试,但更新取决于每个测试需求的HTTP配置?
这是不可能的.服务器对象没什么用处.
using (var server = TestServer.Create<Startup>())
{
var data = server.HttpClient.GetAsync("/api/data);
}
Run Code Online (Sandbox Code Playgroud)
我想要为CRUD集成测试做什么是存根服务方法
// Do it ONE time fall ALL tests
WebApiConfig.Register(config);
WebServicesConfig.Register(config);
// Do it individually for each test, Update DI registerations with Fake components per test method
var builder = new ContainerBuilder();
var mockContext = new Mock<TGBContext>();
var mockService = new Mock<SchoolyearService>(mockContext.Object);
mockService.Setup<Task<IEnumerable<SchoolyearDTO>>>(c => c.GetSchoolyearsAsync()).Returns(Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));
// builder.RegisterInstance<TGBContext>(); ****** NO NEED for this it works without registering the ctor parameter dependency
builder.RegisterInstance<SchoolyearService>(mockService.Object);
builder.Update(((AutofacWebApiDependencyResolver)config.DependencyResolver).Container as IContainer);
Run Code Online (Sandbox Code Playgroud)
目前,我被迫为每个Test方法创建一个TestServer.
这是一个总开销的时间.
解
使HttpConfiguration静态,此代码应该工作:
var builder = new ContainerBuilder();
var mockContext = new Mock<TGBContext>();
var mockService = new Mock<SchoolyearService>(mockContext.Object);
mockService.Setup<Task<IEnumerable<SchoolyearDTO>>>(c => c.GetSchoolyearsAsync()).Returns(Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));
builder.RegisterInstance<SchoolyearService>(mockService.Object);
builder.Update(((AutofacWebApiDependencyResolver)Configuration.DependencyResolver).Container as IContainer);
Run Code Online (Sandbox Code Playgroud)
如果您想为所有测试启动一次 OWIN 服务器。
private static readonly TestServer _webServer = TestServer.Create<Startup>();
protected static TestServer WebServer { get { return _webServer; } }
这应该可以解决所有测试运行时仅实例化一次 Web 服务器的问题。如果您不想这么早初始化 Web 服务器,您可以使用延迟实例化等。但重点是使其静态并在定义时初始化它本身,以便每个应用程序域只使用一次。
至于在单元测试中访问 HttpConfiguration ..这是一种可能的方法..
public static HttpConfiguration HttpConfiguration { get; private set; }
在 Startup.cs 类的 configure 方法中初始化此变量。
HttpConfiguration = new HttpConfiguration();
HttpConfiguration.MapHttpAttributeRoutes();
// do more stuff.. setting resolver etc.
// and then finally
app.UseWebApi(HttpConfiguration);
Run Code Online (Sandbox Code Playgroud)此 HttpConfiguration 属性是您的 Web api 的配置,因为我们将其设为公共属性,所以它应该可以在您的测试项目和所有测试中访问。
Startup.HttpConfiguration
Run Code Online (Sandbox Code Playgroud)您可以访问它来修改依赖项解析器定义等。
Startup.HttpConfiguration.DependencyResolver
Run Code Online (Sandbox Code Playgroud)
请注意,即使在初始化 Web 服务器之后,您也可以更新 DependencyResolver 定义...更新的定义仍然有效。