问题
In nUnit 3, there's been considerable changes made, among which the ExpectedException has been dropped to be replaced by the assertion model.
I've found this and this example but the recommendation is to use Assert.That() instead so I want to use this approach as shown below.
//Arrange
string data = "abcd";
//Act
ActualValueDelegate<object> test = () => data.MethodCall();
//Assert
Assert.That(test, Throws.TypeOf<ExceptionalException>());
However, I'd like to test the assert for a number of different parameters but I can't seem to get it to work. I've tried the following.
List<List<Stuff>> sets = new[] { 0, 1, 2 }
.Select(_ => Enumerable.Repeat(new Stuff(_), _).ToList())
.ToList();
Assert.Throws(() => Transform.ToThings(new List<Stuff>()));
The above works as to creating the list of lists, as desired and testing the Transform.Stuff() call. However, I haven't figured out a way to plug sets into things.
Is it possible? Where are the examples? (Most of the searches drown in nUnit 2.x and on the official documentation site, I see nothing that helps me.)
回答1:
You should look into using the TestCaseSource attribute to define the inputs to your method:
[TestCaseSource("StuffSets")]
public void ToThings_Always_ThrowsAnException(List<Stuff> set)
{
// Arrange
// Whatever you need to do here...
// Act
ActualValueDelegate<object> test = () => Transform.ToThings(set);
// Assert
Assert.That(test, Throws.TypeOf<SomeKindOfException>());
}
public static IEnumerable<List<Stuff>> StuffSets =
{
get
{
return new[] { 0, 1, 2 }
.Select(_ => Enumerable.Repeat(new Stuff(_), _).ToList())
.ToList();
}
};
This will invoke ToThings_Always_ThrowsAnException
once for each List<Stuff>
that is returned from StuffSets
(here, three times).
来源:https://stackoverflow.com/questions/39660806/how-to-handle-multiple-exception-testing-in-nunit-3-according-to-arrange-act-ass