问题
I am using TestCaseSource on NUnit 2.6.1 to test the same Asserts with different object class constructor parameters.
I mean,
[Test, TestCaseSource("myConstructorsForMale")}
public void CheckMale(Person p)
{
Assert.That(p.IsMale);
}
static Person[] myConstructorsForMale =
{
new Person("John"),
new Person(isMale=true),
new Person("Doe")
};
Ok, all is runing fine, but this is the result I received on the NUnit Console:
- CheckMale
- CheckMale(Person)
- CheckMale(Person)
- CheckMale(Person)
So I don't know what is the test executed on every iteration and if any of them fail I cannot get what is the failing test.
My question is: Are there any way to identify with a comment or something similar what is the parameter being passed to the test ? (in TestCaseSource Attribute way of do)
Thanks.
回答1:
If case of using 'native' NUnitor ReSharper as a test runner you can override ToString
method so that you have good Person definitions.
For example, your testing code could look like:
public class PersonTests
{
[Test, TestCaseSource("myConstructorsForMale")]
public void CheckMale(Person p)
{
Assert.That(p.IsMale);
}
static Person[] myConstructorsForMale =
{
new Person("John"),
new Person{IsMale=true},
new Person("Doe")
};
}
Person class could be like:
public class Person
{
public Person(string name)
{
this.Name = name;
}
public Person() { }
public string Name { get; set; }
public bool IsMale { get; set; }
public override string ToString()
{
return string.Format("Name:{0};IsMale:{1}", Name, IsMale);
}
}
The result window will look like this:
I also checked it on native NUnit test runner, which you probably use. It also displays Persons nicely:
回答2:
Riffing on Ilya Ivanov's answer, if you don't want to modify the class under test just to test it, you could put the "to string" logic in the test fixture.
Add a method to the fixture like:
IEnumerable<TestCaseData> PersonTestCases()
{
myConstructorsForMale.Select(
p => new TestCaseData(p).SetName(string.Format("Name:{0};IsMale:{1}" ,p.Name, p.IsMale));
);
}
This creates a TestCaseData
instance for each Person in your myConstructorsForMale
list. The trick is that it sets the Name
property of the TestCaseData
instance to tell the test runner what to display.
Some test runners might work better with SetDescription
rather than SetName
.
Then modify your TestCaseSource
attribute to:
[Test, TestCaseSource("PersonTestCases")]
This should result in something like:
- CheckMale
- Name:;IsMale:True
- Name:Doe;IsMale:False
- Name:John;IsMale:False
来源:https://stackoverflow.com/questions/12974749/c-sharp-nunit-parameterized-testcasesource-value-identification