Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ActionFilterAttributes with MSpec

I'm currently trying to grasp MSpec, mainly to learn new ways of (T/B)DD to be able to make an educated decision on which technology to use. Previously, I've mostly (read: only) used the built-in MSTest framework with Moq, so BDD is quite new for me.

I'm writing an ASP.NET MVC app, and I want to implement PRG. Last time I did this, I used action filters to export and import ModelState via TempData, so that I could return a RedirectResult and the validation errors would still be there when the user got the view. I tested that scenario by verifying two things:

a) That the ExportModelStateAttribute I had written was applied (among tests for my controller)
b) That the attribute worked (among tests for action filter attributes)

However, in BDD I've understood I should be even more concerned with behavior, and even less with implementation. This means I should probably just verify that the model state is in tempdata when the action has finished executing - not necessarily that it's done via an attribute.

To further complicate things, attributes are not run when calling the action directly in the test, so I can't just call the action and see if the job's been done.

How should I spec/test this in MSpec?

like image 522
Tomas Aschan Avatar asked Nov 15 '22 10:11

Tomas Aschan


1 Answers

Filters are cross cutting concerns and as such you should test the behaviour of the filter independently from where it is applied (otherwise you duplicate a lot of testing ).

You can still express the desired behaviour in your controller tests ( model state is stored in temp data ), but the test can assert the existence of the attribute ( could be encapsulated in a a behaviour maybe? ).

As an aside: ASP.NET MVC is designed with the convention of returning the view if the model state contains errors. Using PRG in these scenarios does make sense as PRG is designed to stop duplicate form submission and processing ( i.e. of a valid request ). When a user posts an invalid form, you check for errors before you start processing the request therefore stopping the users request from being processed.

like image 154
Neal Avatar answered Dec 11 '22 01:12

Neal