且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在xUnit.net测试运行设置code只有一次

更新时间:2023-02-11 10:35:03

在此之后的xUnit讨论主题中的指导一>,它看起来像你需要实现灯具的构造,也实现IDisposable。下面是表现你想要的方式完整的示例:

Following the guidance in this xUnit discussion topic, it looks like you need to implement a constructor on the Fixture and also implement IDisposable. Here's a complete sample that behaves the way you want:

using System;
using System.Diagnostics;
using Xunit;
using Xunit.Sdk;

namespace xUnitSample
{
    public class SomeFixture : IDisposable
    {
        public SomeFixture()
        {
            Console.WriteLine("SomeFixture ctor: This should only be run once");
        }

        public void SomeMethod()
        {
            Console.WriteLine("SomeFixture::SomeMethod()");
        }

        public void Dispose()
        {
            Console.WriteLine("SomeFixture: Disposing SomeFixture");
        }
    }

    public class TestSample : IUseFixture<SomeFixture>, IDisposable
    {
        public void SetFixture(SomeFixture data)
        {
            Console.WriteLine("TestSample::SetFixture(): Calling SomeMethod");
            data.SomeMethod();
        }

        public TestSample()
        {
            Console.WriteLine("This should be run once before every test " + DateTime.Now.Ticks);
        }

        [Fact]
        public void Test1()
        {
            Console.WriteLine("This is test one.");
        }

        [Fact]
        public void Test2()
        {
            Console.WriteLine("This is test two.");
        }

        public void Dispose()
        {
            Console.WriteLine("Disposing");
        }
    }
}

当从控制台亚军运行此,你会看到下面的输出:

When running this from the console runner, you'll see the following output:

D:\\的xUnit> xunit.console.clr4.exe Test.dll的/ HTML foo.htm xUnit.net
  控制台测试运行器(64位.NET 4.0.30319.17929)版权所有(C)
  2007-11微软公司。

D:\xUnit>xunit.console.clr4.exe test.dll /html foo.htm xUnit.net console test runner (64-bit .NET 4.0.30319.17929) Copyright (C) 2007-11 Microsoft Corporation.

xunit.dll:版本1.9.1.1600测试组装:Test.dll的

xunit.dll: Version 1.9.1.1600 Test assembly: test.dll

SomeFixture构造函数:这应该只运行一次

SomeFixture ctor: This should only be run once

测试完成:2

SomeFixture:处置SomeFixture

SomeFixture: Disposing SomeFixture

2总,0失败,0跳过了0.686秒

2 total, 0 failed, 0 skipped, took 0.686 seconds

然后,当你破解打开测试输出文件foo.htm,你会看到其他的测试输出。

Then, when you crack open the test output file foo.htm, you'll see the other test output.