How to write a unit test for your custom attribute which extends ActionFilterAttribute in c# .net core?

Nuthan Murarysetty
1 min readFeb 14, 2022
Add unit test for your custom attribute using C#

From this article, you will gain knowledge on how to write a unit test for your custom attribute class which extends ActionFilterAttribute class

We include this override onActionExecuting method and written a unit test on this.

Syntax: <Name>Attribute follows naming convention for any attribute class during creation but while using just with <Name>

The following code snippet has custom attribute,

Custom Attribute which extends ActionFilterAttribute class

Requirement : Write a unit test method which has error and method should return BadRequestobjectresult object.

The following unit test configures action context and other dependencies before we actually called our actual method,

Unit test method for ActionContext

Reference Links: Followed using the below reference links and implemented it in my main project. Even the above sample code which took it from the following reference to consolidate in one place. If you want to go behind this then please check the following links for detailed reference.

https://stackoverflow.com/questions/46162940/how-to-unit-test-actionfilterattributehttps://www.thecodebuzz.com/unit-test-mock-actionfilter-asp-net-core-actionexecutingcontext-moq/https://makolyte.com/aspdotnet-core-how-to-unit-test-an-action-filter/

— Happy Learning :)

--

--

Nuthan Murarysetty

I love sharing things what I know to others and passionate in photography.