Seb Nilsson
Seb Nilsson

Reputation: 26458

C#: Using Conditional-attribute for tests

Are there any good way to use the Conditional-attribute in the context of testing?

My thoughts were that if you can do this:

[Conditional("Debug")]
public void DebugMethod()
{
    //...
}

Maybe you could have some use for: (?)

[Conditional("Test")]
public void TestableMethod()
{
    //...
}

Upvotes: 4

Views: 3170

Answers (4)

Simon P Stevens
Simon P Stevens

Reputation: 27509

The other problem with this is that you may want to run your unit tests on your release builds. (We certainly do).

Upvotes: 1

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

If the test code is not part of the product it should not be in the product code base. I have seen projects trying to include unit tests in the same project as the tested objects, and using #if statements to include them only in debug builds only to regret it later.

One obvious problem would be that the application project gets a reference to the unit testing framework. Even though you may not need to ship that framework as part of your product (if you can guarantee that no code in the release build will reference it), it still smells a bit funny to me.

Let test code be test code and production code be production code, and let the production code have no clue about it.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064324

I'd accept Mehrdad's answer - I just wanted to give more context on when you might use these attributes:

Things like [Conditional] are more generally used to control things like logging/tracing, or interactions with an executing debugger; where it makes sense for the calls to be in the middle of your regular code, but which you might not want in certain builds (and #if... etc is just so ugly and easy to forget).

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422320

I don't see a use when there's a better alternative: Test Projects.

Use NUnit or MSTest to achieve this functionality in a more graceful way.

Upvotes: 4

Related Questions