Search code examples
c#nunit

NUnit CustomAttribute always shows the TestName as AdHockTestMethod. How do I fix this?


I developed a CustomAttribute class for my Test Project called like this:

[Test, CustomAttribute]

It's job is to get the current Test name upon entry, using this code:

var testName = TestContext.CurrentContex.Test.Name

Every time it's called there is at least one instance of this string:

AdHockTestMethod

I never knew why; but I put in a filter to ignore it as that is not the Test Name I need. (It appears to be an NUnit internals thing).

  • NUnit calls this CustomAttribute multiple times and eventually the Test Name is correct.
  • Up until today, the CustomAttribue code with the AdHockTestMethod filter worked.
  • But today the TestName is always AdHocTestMethod
  • I can't seem to find out why this is happening. Is there something else I'm missing?

My Test Code is simply something like this:

[TestFixture]
public class TestClassName: BaseClass {
[Test, CustomAttribue]
public async Task TestName(){
}
   // do something asynchronous here
}

Solution

  • The root cause turned out to be the async method declaration shown above. As soon as I removed that part and used Task.Run with Async (inside the method) everything worked. The updated code looked like this:

    [Test, CustomAttribute]
    public void TestName(){
    
      Task.Run(async ()=> await doSomething());
    }
    

    TestContext.CurrentContext.Test.Name self corrected after making this change. I have no idea why this worked.