TestOf
TestOfAttribute is used to specify the class or type that a test fixture or test method is testing. This metadata helps document the relationship between tests and the code under test, and can be used by test runners and reporting tools to organize test results.
What It Does
TestOf is informational only. It has no effect on how NUnit discovers, orders or executes tests, and it does not
check that the named type exists or is actually exercised by the test. The attribute simply records a TestOf property
on the test, holding the full name of the type. That property appears in the XML result file and is available to
runners, report generators and other tools that display test properties. It can also be used to select tests by
property in the console runner's Test Selection Language, in the same way as any other
property.
Constructors
TestOfAttribute(Type type)
TestOfAttribute(string typeName)
| Parameter | Type | Description |
|---|---|---|
type |
Type |
The type that is being tested. The full type name is stored. |
typeName |
string |
The name of the type that is being tested. |
Applies To
| Test Methods | Test Fixtures (Classes) | Assembly |
|---|---|---|
| ✅ | ✅ | ✅ |
Alternative Syntax
TestOf can also be specified as a named parameter on [TestFixture] or [Test] attributes:
[TestFixture(TestOf = typeof(MyClass))]
[Test(TestOf = typeof(MyClass))]
Examples
Using the Attribute
[TestFixture]
[TestOf(typeof(Calculator))]
public class CalculatorTests
{
[Test]
public void Add_TwoPositiveNumbers_ReturnsSum()
{
var calculator = new Calculator();
Assert.That(calculator.Add(2, 3), Is.EqualTo(5));
}
[Test]
[TestOf(typeof(AdvancedCalculator))]
public void SquareRoot_PositiveNumber_ReturnsCorrectResult()
{
// This specific test is for AdvancedCalculator
var calculator = new AdvancedCalculator();
Assert.That(calculator.SquareRoot(4), Is.EqualTo(2.0));
}
}
Using String Names
[TestFixture]
[TestOf("Snippets.NUnit.Attributes.Calculator")]
public class CalculatorTestsWithStringName
{
[Test]
[TestOf(nameof(AdvancedCalculator))]
public void TestUsingNameof()
{
// Using nameof() provides compile-time safety
var calculator = new AdvancedCalculator();
Assert.That(calculator.Add(1, 1), Is.EqualTo(2));
}
}
Using Named Parameter Syntax
[TestFixture(TestOf = typeof(Calculator))]
public class CalculatorTestsWithNamedParameter
{
[Test(TestOf = typeof(AdvancedCalculator))]
public void TestUsingNamedParameterSyntax()
{
var calculator = new AdvancedCalculator();
Assert.That(calculator.SquareRoot(9), Is.EqualTo(3.0));
}
}
Notes
- This attribute inherits from
PropertyAttributeand sets theTestOfproperty with the full type name. - Using
typeof()is preferred over string names as it provides compile-time type checking. - For string names, consider using
nameof()for compile-time safety when the type is accessible. - Multiple
TestOfattributes can be applied to the same element when a test covers multiple types.