Thursday, July 28, 2011

Unit Test DisplayFormat attribute HtmlHelper

    Previously, I wrote about how to mock a ViewEngine for one of my unit tests. Today, I came across a question on StackOverflow asking about how to unit test the out put of DataAnnotation attribute DisplayFormat. I'm very interested in Unit Test so I decide to find the answer, another reason is to increase my reputation on StackOverflow :D. Honestly, I don't exactly know the reason why to test the output...

Tuesday, July 19, 2011

Save some lines for your Razor view

We all know that we should not put logic in the MVC view. If we have to do something base on a complex condition, we should better make a HtmlHelper method for that logic. In an attempt to remove some simple if/else statement on the view by using some extention method. Let's say we have something like below in the view: @if (!Request.IsAuthenticated) { Html.RenderPartial("LoginBox"); } I attempt to make it look like:   @{...

How to mock UrlHelper?

Sometime, you need to write unit test for an action method that needs a UrlHelper. But I'm sure you will never can mock that stuff since it's a concrete class and it's methods are not virtual. Let's say we have following action method and want to test it: [Authorize] public ActionResult LogOnAs(Guid userId, string returnUrl) { // Logic to login user by Id ... if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); ...

Wednesday, July 6, 2011

Never give a chance to make something wrong

Recectly, I've penetrated the truth that if you don't want others do something (bad), never ever give them a chance to do that. It's true in both my real life and in programming. Since my blog is just about software programming, I would like to write about some funny mistakes that people often make. Well, I did make some of them in the past :D 1/ You may forget about the ability of the constructor. Let's look at following code: public...