C# Nancy OWIN测试交互
我试图弄明白为什么我们的集成测试不是独立的 每个测试的基本部分是:C# Nancy OWIN测试交互,c#,nunit,owin,autofac,nancy,C#,Nunit,Owin,Autofac,Nancy,我试图弄明白为什么我们的集成测试不是独立的 每个测试的基本部分是: var builder = new ContainerBuilder(); // IoC registrations, typically SingleInstance lifetimes or RegisterInstance var browser = new Browser(new CustomBootstrapper(builder)); // browser.Post... // Assertions 每个测试都使用
var builder = new ContainerBuilder();
// IoC registrations, typically SingleInstance lifetimes or RegisterInstance
var browser = new Browser(new CustomBootstrapper(builder));
// browser.Post...
// Assertions
每个测试都使用新的ContainerBuilder和浏览器实例
我们的一个测试在独立运行时通过,但如果与另一个类似的测试一起运行则失败。这在两个不同的测试运行程序(TestDriven.Net和JetBrains)中发生
通过检测,我可以通过检查HashCodes看到第一个测试使用的对象和IoC容器注入的对象在第二个测试中出现(并且与在那里创建的对象不匹配)。方法在错误的对象上调用,因此测试失败
代码不使用静态成员
我是否误解了南希、南希、测试或奥文的工作方式?这些测试如何相互影响
根据请求,更多详细信息:
[Test]
public void Test1()
{
var organizationCache = new OrganizationCache();
// Logs Creating OrganizationCache with HashCode:43641814 (varies by run)
organizationCache.AddOrganization(organization);
ContainerBuilder builder = AutofacTestContainerBuilderFactory.CreateTestContainerBuilder();
builder.RegisterInstance(organizationCache);
var browser = new Browser(new CustomBootstrapper(builder));
BrowserResponse browserResponse = browser.Post(
"/api/...",
with => with.JsonBody(model));
browserResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
}
在单独的TestFixture类中,没有设置/拆卸:
[Test]
public void Test2()
{
var organizationCache = new OrganizationCache();
// Logs Creating OrganizationCache with HashCode:5337202 (varies by run)
organizationCache.AddOrganization(organization);
ContainerBuilder builder = AutofacTestContainerBuilderFactory.CreateTestContainerBuilder();
builder.RegisterInstance(organizationCache);
var browser = new Browser(new CustomBootstrapper(builder));
TestHelpers.Authenticate(browser); // log in (does a browser.Post)
BrowserResponse browserResponse = browser.Post(
"/api/...",
with => with.JsonBody(model));
browserResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
// Passes if run independently, fails if run with other test
// When run with other test, system under test logs both OrganizationCache HashCodes during this test
}
基于Cookie的会话是否会影响这一点?(注意:我尝试删除CookieBasedSessions.Enable
,并在管道中单独和一起创建一个新的会话
;这不会影响问题。)
在每次测试后处理customBootstrapper也没有什么区别
(
CustomBootstrapper
没有静态字段,是从AutofacNancyBootstrapper
派生的。在这里发布太长了。)我们的一位开发人员在代码中发现了这个问题
using Nancy.Authentication.Forms;
public class UserMapper : IUserMapper
{
public static IOrganizationService OrganizationService { get; set; }
// ...
}
ioorganizationservice
的实现将OrganizationCache
注入到其构造函数中
静态字段是罪魁祸首。您是使用清理这些测试并设置来初始化它们,还是此字段位于方法中?您可以显示更多代码吗?也就是说,当一起运行时,使另一个中断的单元测试和使另一个中断的单元测试?如果您正在使用安装和拆卸方法,也可以使用安装和拆卸方法says@andreasnico和其他-请查看我的编辑。组织来自何处,TestHelpers.Authenticate看起来像什么,您如何在模块中使用组织,您的模块看起来像什么,自定义引导程序看起来像什么,您发布的模型是什么样子的