I have an MVC controller that contains the following post method:
[HttpPost]
[PermissionLevel(PermissionLevel.Manage)]
public async Task<IActionResult> CreateUserAsync([FromBody] User user)
{
user = await _usersService.CreateUserAsync(user);
return Created($"{_microservices.Users}/{user.Id}", user);
}
I'm trying to unit test this controller (using MSTest), and one of the tests I want to make checks that the correct route and permission attributes have been applied to the method. I also want to ensure that no other attributes are present on the method, and I'm currently doing this by checking the count of attributes on the method:
[TestMethod]
public void CreateUserAsync_HasTwoAttributes()
{
int count = typeof(UsersController).GetMethod(nameof(UsersController.CreateUserAsync))
.GetCustomAttributes()
.Count();
Assert.AreEqual(2, count);
}
This has worked fine elsewhere in my application (for properties), but when I run the tests the assert fails saying that there are actually 4 attributes on the method:
{System.Runtime.CompilerServices.AsyncStateMachineAttribute}
{System.Diagnostics.DebuggerStepThroughAttribute}
{Microsoft.AspNetCore.Mvc.HttpPostAttribute}
{Permissions.Models.Filters.PermissionLevelAttribute}
Where do the AsyncStateMachine-
and DebuggerStepThrough-
attributes come from? Is there a way I can not include them and only look at attributes that are explicitly declared on the controller method?
I'm using:
Any help would be appreciated :)
Where do the AsyncStateMachine- and DebuggerStepThrough- attributes come from?
Those extra attributes are added at compile time. async adds the AsyncStateMachineAttribute
When a method (MethodName) has the Async or async modifier, the compiler emits IL that includes a state machine structure. This structure contains the code in the method. That IL also contains a stub method (MethodName) that calls into the state machine. The compiler adds the AsyncStateMachine attribute to the stub method so that tools can identify the corresponding state machine. Details of the emitted IL might change in future releases of the compilers.
and debug mode adds the other.