Evgeniy Miroshnichenko
Evgeniy Miroshnichenko

Reputation: 1865

How to pass NULL value to ValuesAttribute of the test method?

When I try to pass Null value to nunit ValuesAttribute I get an error.

If will run this test, all test methods of the class will`t be executed:

[TestFixture]
public class UrlSectionsTests {

    [Test]
    public void SetRoot_Throws_ArgumentNullExcpetion(
        [Values(null)] TestUrlRootSection rootSection
        )
    {
        Assert.Throws<ArgumentNullException>(() => 
            this.urlSections.Root = rootSection);
    }
}

Is there a way to pass NULL value to ValuesAttribute?

Upvotes: 0

Views: 3253

Answers (3)

Lionia Vasilev
Lionia Vasilev

Reputation: 12747

You better use an appropriate tests naming conventions such as UnitOfWork_StateUnderTest_ExpectedBehavior(). In this particular case you may rename function to Root_SetToNull_ThrowsArgumentNullExcpetion(). Check Naming standards for unit tests article by Roy Osherove for more information.

If you try to run this test case using NUnit Console Runner you will see that exception is thrown by NUnit Framework:

System.NullReferenceException: Object reference not set to an instance of an object. at NUnit.Framework.Internal.ParamAttributeTypeConversions.GetData(Object[] data, Type targetType) at NUnit.Framework.Internal.Builders.ParameterDataSourceProvider.GetDataFor(IParameterInfo parameter) at NUnit.Framework.CombiningStrategyAttribute.BuildFrom(IMethodInfo method, Test suite) at NUnit.Framework.Internal.Builders.DefaultTestCaseBuilder.BuildFrom(IMethodInfo method, Test parentSuite) at NUnit.Framework.Internal.Builders.NUnitTestFixtureBuilder.AddTestCasesToFixture(TestFixture fixture) at NUnit.Framework.Internal.Builders.NUnitTestFixtureBuilder.BuildFrom(ITypeInfo typeInfo) at NUnit.Framework.Internal.Builders.DefaultSuiteBuilder.BuildFrom(ITypeInfo typeInfo)

This is probably a bug. But I don't see any strong reason to use [Values(null)] anyway, because you can safely turn any test case parameter that is always null to local variable or remove entirely.

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61982

If the ValuesAttribute type has a constructor overload with signature ValuesAttribute(params object[] x), that overload will preferred in its non-expanded form. I.e., your bare null will be seen as a null of type object[]. To avoid that, use:

[Values((object)null)]

Upvotes: 1

Charlie
Charlie

Reputation: 13736

I agree with CodingYoshi that you don't have much reason to use ValuesAttribute here. However, you may have uncovered a bug, in which case it should be reported and fixed!

Upvotes: 1

Related Questions