首页 > 解决方案 > nunit - 在类上使用多个 TestFixtureSource

问题描述

我正在尝试用 nunit 做一些事情,但我不确定它是否可能。基本上我试图通过使用 TestFixtureSource 来减少我的代码设置。我写了这个:

SomeTestClass.cs

[TestFixtureSource(typeof(FixtureData1), "FixtureParams")]
[TestFixtureSource(typeof(FixtureData2), "FixtureParams")]
    public class SomeTestClass: BaseRepositoryTests
    {
        private readonly Foo _foo;
        private readonly Bar _bar;

        public SomeTestClass(Foo foo, Bar bar) 
        {
            _foo = foo;
            _bar = bar;
        }

        [Test]
        public async Task SomeTest()
        {

        }
    }

Foo.cs

public class Foo
    {
        public static IEnumerable<Foo> FixtureParams
        {
            get
            {
                yield return new Foo
                {
                    FooId = 0,
                    FooName= "meh",
                };
            }
        }
    }

酒吧.cs

 public class Bar
    {
        public static IEnumerable<Bar> FixtureData
        {
            get
            {
                yield return new Bar
                    {Email = "test.user@google.com", FirstName = "test", Surname = "user"};
            }
        }
    }

我收到此错误:

Message: OneTimeSetUp: No suitable constructor was found

有人知道这在nunit中是否可行?

标签: c#nunit

解决方案


根据文档,您似乎无法做您想做的事情

这是一个例子

[TestFixtureSource(typeof(FixtureArgs))]
public class SomeTestClass: BaseRepositoryTests {
    private readonly Foo _foo;
    private readonly Bar _bar;

    public SomeTestClass(Foo foo, Bar bar)  {
        _foo = foo;
        _bar = bar;
    }

    [Test]
    public async Task SomeTest() {
        //...
    }
}


class FixtureArgs: IEnumerable {
    public IEnumerator GetEnumerator() {
        yield return new object[] { 
            new Foo { FooId = 0, FooName= "meh" }, new Bar { Email = "test.user@google.com", FirstName = "test", Surname = "user"} 
        };

        yield return new object[] { 
            new Foo { FooId = 1, FooName= "meh" }, new Bar { Email = "test.user@google.com", FirstName = "test", Surname = "user"} 
        };

        //...
    }
}

这是另一个

[TestFixtureSource(typeof(AnotherClass), "FixtureArgs")]
public class SomeTestClass: BaseRepositoryTests {
    private readonly Foo _foo;
    private readonly Bar _bar;

    public SomeTestClass(Foo foo, Bar bar)  {
        _foo = foo;
        _bar = bar;
    }

    [Test]
    public async Task SomeTest() {
        //...
    }
}

class AnotherClass
{
    static object [] FixtureArgs = {
        new object[] { new Foo { FooId = 0, FooName= "meh" }, new Bar { Email = "test.user@google.com", FirstName = "test", Surname = "user"}  },
        new object[] {  new Foo { FooId = 1, FooName= "meh" }, new Bar { Email = "test.user@google.com", FirstName = "test", Surname = "user"}  }
    };
}

参考TestFixtureSource 属性


推荐阅读