NUnit TestCaseSource pass value to factory
Asked Answered
B

2

6

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?

Bifurcate answered 18/2, 2010 at 10:26 Comment(0)
B
2

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

Barber answered 30/10, 2010 at 3:58 Comment(0)
C
1

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.

Corves answered 12/12, 2011 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.