Reputation: 1484
We have a test framework based on NUnit where we use ITestAction. We have several test attributes which implement this interface. The ITestAction interface implements BeforeTest and AfterTest. For some reason, we have some AfterTest implementations assert some things and consequently they might throw preventing other AfterTest methods from other attributes to be invoked. Therefore, this imposes a problem.
My question is: is it a good idea to have AfterTest assert at all?
Can I force NUnit to execute all AfterTest even though some of them throw?
Is there any other solutions?
Upvotes: 1
Views: 205
Reputation: 11
Your problem may be that you are running the assertions for suites (e.g. at the class/assembly level), not just for individual test methods.
You may need to wrap your assertions in if (!test.IsSuite) { ... }
.
In general it is fine to Assert in AfterTest. The AfterTestActionCommand in NUnit specifically handles the case where assertions are made in AfterTest.
Upvotes: 0
Reputation: 2633
No it is not a good idea. Those methods should be used to do setup before the test is run and to do clean up after the test has run. Keep your asserts in the tests.
From nunit.org about action attributes:
- Action Attributes are a feature of NUnit designed to better enable composability of test logic.
- Action Attributes allow the user to create custom attributes to encapsulate specific actions for use before or after any test is run.
As is stated in the quote, the purpose of the action attribute is for you to define some custom setup or teardown logic that can be combined with other setup or teardown logic you have defined in a different action attribute.
These attributes should be independent of the actual tests otherwise you are creating a dependency between the action attribute and the tests. This breaks the compositional design and is not what action attributes are intended for.
The definition of a unit test:
A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.
From this definition we see that asserts are a core part of the unit test itself and should be kept inside the test (not outside). It needs to be independent.
Upvotes: 2