开发者

Make MSTest respect [Conditional()] attribute?

开发者 https://www.devze.com 2023-01-04 19:59 出处:网络
I\'m using VS2010, I have the following method call: [Conditional(\"DEBUG\")] public void VerboseLogging() { }

I'm using VS2010, I have the following method call:

[Conditional("DEBUG")]
public void VerboseLogging() { }

public void DoSomething() {
    VerboseLogging();
    Foo();
    Bar();
}

Then I have a unit test for the DoSomething method which checks that it emits proper logging.

[Conditional("DEBUG"), TestMethod()]
public void EnsureVerboseLog() {
    DoSomething();
    VerifyVerboseLoggingCalled(); // <-- fail in release builds since VerboseL开发者_JS百科ogging() calls get eliminated.
}

It seems that MSTest only sees TestMethod and executes it (generating failed test) even though I've marked it with Conditional("DEBUG") and compile it in release mode.

So, is there a way to exclude certain tests depending on compilation constant other than #if?


The ConditionalAttribute does not affect whether or not a method is compiled into an application. It controls whether or not calls to the method are compiled into the application.

There is no call to EnsureVerboseLog in this sample. MSTest just sees a method in the assemlby with the TestMethod attribute and correctly executes it. In order to prevent MSTest from running the method you will need to do one of the following

  1. Not compile it into your application (possible through #if's)
  2. Not annotate it with the TestMethod attribute


So, is there a way to exclude certain tests depending on compilation constant other than #if?

I'd use the #if - it's readable.

[TestMethod]
#if !DEBUG
[Ignore]
#endif
public void AnyTest()
{
    // Will invoke for developer and not in test-server!
}

HTH..


A work around is to set the Priority attribute to -1 to your method. Then run mstest with "minpriority:0" as an argument.

[TestMethod()]
[Priority(-1)]
public void Compute_Foo()
{
    This method will not be executed
}


If you want to be able to conditionally run different tests, you will probably want to use the [TestCategory] attribute:

[TestMethod]
[TestCategory("SomeCategory")]
public void SomethingWorks()
{
    ...
}

And then use the filter parameter to include or exclude the categories:

dotnet test --filter "TestCategory=SomeCategory"
dotnet test --filter "TestCategory!=SomeCategory"
0

精彩评论

暂无评论...
验证码 换一张
取 消