NUnit TestCaseSource pass value to factory

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 13:16:51

问题


I'm using the NUnit 2.5.3 TestCaseSource attribute and creating a factory to generate my tests. Something like this:

[Test, TestCaseSource(typeof(TestCaseFactories), "VariableString")]
public void Does_Pass_Standard_Description_Tests(string text)
{
    Item obj = new Item();
    obj.Description = text;
}

My source is this:

public static IEnumerable<TestCaseData> VariableString
{
    get
    {
        yield return new TestCaseData(string.Empty).Throws(typeof(PreconditionException))
            .SetName("Does_Reject_Empty_Text");
        yield return new TestCaseData(null).Throws(typeof(PreconditionException))
            .SetName("Does_Reject_Null_Text");
        yield return new TestCaseData("  ").Throws(typeof(PreconditionException))
            .SetName("Does_Reject_Whitespace_Text");
    }
}

What I need to be able to do is to add a maximum length check to the Variable String, but this maximum length is defined in the contracts in the class under test. In our case its a simple public struct:

   public struct ItemLengths
    {
        public const int Description = 255;
    }

I can't find any way of passing a value to the test case generator. I've tried static shared values and these are not picked up. I don't want to save stuff to a file, as then I'd need to regenerate this file every time the code changed.

I want to add the following line to my testcase:

yield return new TestCaseData(new string('A', MAX_LENGTH_HERE + 1))
    .Throws(typeof(PreconditionException));

Something fairly simple in concept, but something I'm finding impossible to do. Any suggestions?


回答1:


Change the parameter of your test as class instead of a string. Like so:

public class StringTest { public string testString; public int maxLength; }

Then construct this class to pass as an argument to TestCaseData constructor. That way you can pass the string and any other arguments you like.

Another option is to make the test have 2 arguments of string and int.

Then for the TestCaseData( "mystring", 255). Did you realize they can have multiple arguments?

Wayne




回答2:


I faced a similar problem like yours and ended up writing a small NUnit addin and a custom attribute that extends the NUnit TestCaseSourceAttribute. In my particular case I wasn't interested in passing parameters to the factory method but you could easily use the same technique to achieve what you want.

It wasn't all that hard and only required me to write something like three small classes. You can read more about my solution at: blackbox testing with nunit using a custom testcasesource.

PS. In order to use this technique you have to use NUnit 2.5 (at least) Good luck.



来源:https://stackoverflow.com/questions/2287829/nunit-testcasesource-pass-value-to-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!