views:

52

answers:

2

Stephen Walther recommends that you should provide explicit view names when you want to unit-test them.

I definitely want to test them, but I'm curious whether or not this recommendation is still valid with the release of 1.0.

In the NerdDinner tutorial the tests just check if the viewResult is null. They don't explicitly specify the viewName, which is therefore empty. I would like to remove the view-names provided as strings in the actual code, but these checks seems less useful to me though... (I can't even think of a scenario where the viewResult does return null?!)

A: 

Providing explicit view names matters if controller can return various views. Then you can unit test controller, that it returns one it's supposed to return by name. Otherwise - i don't see the point of using them.

Arnis L.
+1  A: 

There are really two separate questions here. The first is whether or not anything has changed in the MVC framework since Stephen Walther wrote the recommendation which would change the recommendation. The answer to that question is "no."

The second question is whether or not the recommendation is a good practice. I'm going to disagree with Stephen Walther, here. His example is a bit strange. His unit test for the "Index" action attempts to assert that the action returns an explicit view name, when clearly it does not. If I wrote this unit tests, I would instead assert that the view name is equal to empty string. Then the unit test would pass. Instead of asserting that the action specifies a view of a certain name, a unit test would then effectively assert that the action specifies that the view have the same name as the action. This is a legitimate thing to test.

One of the guiding principles behind the MVC framework is convention over configuration. In other words, you should not be required to specify anything which is just the usual default value. The default value of the view name is the same as the action name. The documented behavior of the WebFormsViewEngine is to look for a view with the same name as the action unless a separate view name is specified. Not specifying a view name, therefore, is the same as specifying "use the default view name."

Therefore, I do not think it is a good idea to specify a view name which is the same as the default, and I do not think that using unit testing is a good reason to violate this convention.

Craig Stuntz