I am working on an open source blogging project (with mvc). I try to contribute this as much as I can with TDD approach. Today; I came to a situation that List.ForEach() really helped me to save some lines of code; and I decided to share this :). The project has an entity called Post which represent a post in a blog; and this entity has a field "IsApproved" which basically determines if this post should be displayed or saved but not displayed. The controller has an action method "List" that generates the posts; and send it to the View; however; I would like to test List so that It only sends the IsPublished==true posts to the view. Simplified List method is :
public ActionResult List()
    return View("List",postRepository.Posts.Where(p=>p.IsApproved==true));
My test function for this is:
public void List_Should_Only_Pass_Approved_Posts_To_View()
    IPostRepository repository = new FakePostRepository();
    PostsController controller = new PostsController(repository);
    var view = (ViewResult) controller.List();
    var posts = view.ViewData.Model as IQueryable<Post>;
     posts.ToList().ForEach(c => Assert.True(c.IsApproved == true));
I had to iterate through the list of Posts and confirm that, each of these posts have IsPublished=true. Instead of writing a foreach loop and calling assert for each post; I decided to ListForEach().

Let’s goto MSDN and checkout “List<T>.ForEach()”';  according to the definition; this function performs the specified action on each element of the List<T>; and the declaration of the function is:

public void ForEach(
    Action<T> action

Basically it is taking Action as a parameter; and calling this for each element of the List. In case you are not familiar with this delegate; it is basically any function that takes a single parameter and does not return anything. Going back to my test function; I should be Asserting each element and checking if IsPublished==true or not. An Action<T> delegate could easily be c=>Assert.True(c.IsApproved==true)).
Assert.True(bool condition) is a function which returns void; and takes only 1 parameter which a condition; so I can pass this to the ForEach function and test my assumption.


E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses