<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Sayed Ibrahim Hashimi - MSBuild, Web Deploy (MSDeploy), ASP.NET - mocks</title>
    <link>http://sedodream.com/</link>
    <description>MSBuild, C#, Visual Studio and more</description>
    <language>en-us</language>
    <copyright>Sayed Ibrahim Hashimi</copyright>
    <lastBuildDate>Fri, 26 Mar 2010 05:10:46 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>sayed.hashimi@gmail.com</managingEditor>
    <webMaster>sayed.hashimi@gmail.com</webMaster>
    <item>
      <trackback:ping>http://sedodream.com/Trackback.aspx?guid=e2d2acfd-8a99-42b3-99ff-de085619ce51</trackback:ping>
      <pingback:server>http://sedodream.com/pingback.aspx</pingback:server>
      <pingback:target>http://sedodream.com/PermaLink,guid,e2d2acfd-8a99-42b3-99ff-de085619ce51.aspx</pingback:target>
      <dc:creator>Ibrahim</dc:creator>
      <wfw:comment>http://sedodream.com/CommentView,guid,e2d2acfd-8a99-42b3-99ff-de085619ce51.aspx</wfw:comment>
      <wfw:commentRss>http://sedodream.com/SyndicationService.asmx/GetEntryCommentsRss?guid=e2d2acfd-8a99-42b3-99ff-de085619ce51</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'm working on an application right now which uses some mock classes which were "hand
written" instead of using a mock framework. I haven't had much experience with
using mock frameworks, but I've wanted to learn more about them. There are many mock
frameworks out there, I chose to use <a href="http://code.google.com/p/moq/">moq</a> because
the test cases for <a href="http://www.asp.net/mvc/">ASP.NET MVC</a> use <a href="http://code.google.com/p/moq/">moq</a>.
What I wanted to do was replace the mock class that I created with a moq class. If
you have ever created mock classes before then you probably know that they are pretty
annoying to maintain. What I mean is that if you add a method/property to the interface
which the mock class implements then you have to update the mock just to get it to
build. This is annoying and kinda makes people not to use the mock which then ends
up in ignoring/commenting out test cases. To avoid all of this most mock frameworks,
including moq, just require you to specify behavior for methods/properties which you
are ready to exercise in your test cases. Now I’d like to show you the mock class
that I had. This interface that it is mocking is used to abstract the data store.
</p>
        <pre class="brush: csharp;">internal class MockModelContext :IModelContext
{
    public User CreateUser(User user)
    {
        // if id is not set, set it and just return it
        if (user.Id &lt;= 0)
        {
            user.Id = 1;
        }

        return user;
    }

    public User GetUserByEmail(string email)
    {
        if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException("email"); }

        User user = CreateDummyUser();
        user.Email = email;

        return user;
    }

    public User GetUser(Expression&lt;Func&lt;User, bool&gt;&gt; filter)
    {
        return CreateDummyUser();
    }

    public IList&lt;Task&gt; GetRecentTasks()
    {
        IList&lt;Task&gt; tasks = new List&lt;Task&gt;()
        {
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 01 here",
                Headline="Headline 01 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"&lt;ScriptHere&gt;script&lt;/ScriptHere&gt;",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            },
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 02 here",
                Headline="Headline 02 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"&lt;ScriptHere&gt;script2&lt;/ScriptHere&gt;",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            }
        };

        return tasks;
    }
    protected internal User CreateDummyUser()
    {
        User user = new User()
        {
            Email = "email",
            FirstName = "First",
            LastName = "Last",
            MiddleName = "Middle"
        };

        return user;
    }
    public User GetUserByOpenIdUrl(string openIdUrl)
    {
        throw new NotImplementedException();
    }
    public IList&lt;Task&gt; GetRecentTasks(IEnumerable&lt;string&gt; includeList)
    {
        throw new NotImplementedException();
    }
    public Task AddTask(Task task)
    {
        throw new NotImplementedException();
    }
    public User GetUserById(long id)
    {
        User user = this.CreateDummyUser();
        user.Id = id;

        return user;
    }
    public User SaveUser(User user)
    {
        throw new NotImplementedException();
    }
    public Task GetTaskById(long id)
    {
        throw new NotImplementedException();
    }
}</pre>
        <p>
Take notice of the methods which just throw a <a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx">NotImplementedException</a>,
these are methods that I just added to the interface and haven’t yet written test
cases for. (Yeah I know I’m not following true TDD, but I never claimed to be either).
Now you can compare that to these methods which use moq to create the mock.
</p>
        <pre class="brush: csharp;">private Mock&lt;IModelContext&gt; CreateMockModelContext()
{
    var context = new Mock&lt;IModelContext&gt;();

    context.Setup(c =&gt; c.CreateUser(It.IsAny&lt;User&gt;()))
        .Returns&lt;User&gt;(user =&gt;
        {
            if (user.Id &lt;= 0)
            {
                user.Id = 1;
            }
            return user;
        });

    context.Setup(c =&gt; c.GetUserByEmail(It.IsAny&lt;string&gt;()))
        .Returns&lt;string&gt;(email =&gt;
            {
                if (email == null) { throw new ArgumentNullException("email"); }

                User user = this.CreateDummyUser();
                user.Email = email;

                return user;
            }); ;

    context.Setup(c =&gt; c.GetUserById(It.IsAny&lt;long&gt;()))
        .Returns&lt;long&gt;(id =&gt; 
        {
            User user = new User();
            user.Id = id;
            return user;
        });

    context.Setup(c =&gt; c.GetRecentTasks())
        .Returns(() =&gt;
        {
            IList&lt;Task&gt; tasks = new List&lt;Task&gt;()
            {
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 01 here",
                    Headline="Headline 01 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"&lt;ScriptHere&gt;script&lt;/ScriptHere&gt;",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                },
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 02 here",
                    Headline="Headline 02 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"&lt;ScriptHere&gt;script2&lt;/ScriptHere&gt;",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                }

            };
            return tasks;
        });

    return context;
}
protected internal User CreateDummyUser()
{
    User user = new User()
    {
        Email = "email",
        FirstName = "First",
        LastName = "Last",
        MiddleName = "Middle"
    };

    return user;
}</pre>
        <p>
Since I’m just mocking methods all I’m really doing here is using the moq <a href="http://www.clariusconsulting.net/labs/moq/html/3BFDD309.htm">Setup</a> method
(formerly known as Expect), and the <a href="http://www.clariusconsulting.net/labs/moq/html/312A14EA.htm">Returns</a> method
to implement the behavior that I needed. The key to note here is that if you need
to access the parameter(s) passed into the method, then you will have to used Returns
and pass in a lambda expression that contains the behavior. In that lamdba you can
name the parameter anything you want, but I would suggest you name it the same name
that the method you are mocking names it. This makes it much more understandable what
you are actually doing.
</p>
        <p>
Sayed Ibrahim Hashimi
</p>
      </body>
      <title>MOQ: Comparing hard coded mocks to moq mocks</title>
      <guid isPermaLink="false">http://sedodream.com/PermaLink,guid,e2d2acfd-8a99-42b3-99ff-de085619ce51.aspx</guid>
      <link>http://sedodream.com/2010/03/26/MOQComparingHardCodedMocksToMoqMocks.aspx</link>
      <pubDate>Fri, 26 Mar 2010 05:10:46 GMT</pubDate>
      <description>&lt;p&gt;
I'm working on an application right now which uses some mock classes which were &amp;quot;hand
written&amp;quot; instead of using a mock framework. I haven't had much experience with
using mock frameworks, but I've wanted to learn more about them. There are many mock
frameworks out there, I chose to use &lt;a href="http://code.google.com/p/moq/"&gt;moq&lt;/a&gt; because
the test cases for &lt;a href="http://www.asp.net/mvc/"&gt;ASP.NET MVC&lt;/a&gt; use &lt;a href="http://code.google.com/p/moq/"&gt;moq&lt;/a&gt;.
What I wanted to do was replace the mock class that I created with a moq class. If
you have ever created mock classes before then you probably know that they are pretty
annoying to maintain. What I mean is that if you add a method/property to the interface
which the mock class implements then you have to update the mock just to get it to
build. This is annoying and kinda makes people not to use the mock which then ends
up in ignoring/commenting out test cases. To avoid all of this most mock frameworks,
including moq, just require you to specify behavior for methods/properties which you
are ready to exercise in your test cases. Now I’d like to show you the mock class
that I had. This interface that it is mocking is used to abstract the data store.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;internal class MockModelContext :IModelContext
{
    public User CreateUser(User user)
    {
        // if id is not set, set it and just return it
        if (user.Id &amp;lt;= 0)
        {
            user.Id = 1;
        }

        return user;
    }

    public User GetUserByEmail(string email)
    {
        if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException(&amp;quot;email&amp;quot;); }

        User user = CreateDummyUser();
        user.Email = email;

        return user;
    }

    public User GetUser(Expression&amp;lt;Func&amp;lt;User, bool&amp;gt;&amp;gt; filter)
    {
        return CreateDummyUser();
    }

    public IList&amp;lt;Task&amp;gt; GetRecentTasks()
    {
        IList&amp;lt;Task&amp;gt; tasks = new List&amp;lt;Task&amp;gt;()
        {
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description =&amp;quot;Description 01 here&amp;quot;,
                Headline=&amp;quot;Headline 01 here&amp;quot;,
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = &amp;quot;Name here&amp;quot;,
                NumViews = 3,
                Script = @&amp;quot;&amp;lt;ScriptHere&amp;gt;script&amp;lt;/ScriptHere&amp;gt;&amp;quot;,
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email =&amp;quot;one@hotmail.com&amp;quot;,
                    FirstName=&amp;quot;First&amp;quot;,
                    Id=2,
                    LastName=&amp;quot;Last&amp;quot;,
                    MiddleName=&amp;quot;Middle&amp;quot;,
                }
            },
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description =&amp;quot;Description 02 here&amp;quot;,
                Headline=&amp;quot;Headline 02 here&amp;quot;,
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = &amp;quot;Name here&amp;quot;,
                NumViews = 3,
                Script = @&amp;quot;&amp;lt;ScriptHere&amp;gt;script2&amp;lt;/ScriptHere&amp;gt;&amp;quot;,
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email =&amp;quot;one@hotmail.com&amp;quot;,
                    FirstName=&amp;quot;First&amp;quot;,
                    Id=2,
                    LastName=&amp;quot;Last&amp;quot;,
                    MiddleName=&amp;quot;Middle&amp;quot;,
                }
            }
        };

        return tasks;
    }
    protected internal User CreateDummyUser()
    {
        User user = new User()
        {
            Email = &amp;quot;email&amp;quot;,
            FirstName = &amp;quot;First&amp;quot;,
            LastName = &amp;quot;Last&amp;quot;,
            MiddleName = &amp;quot;Middle&amp;quot;
        };

        return user;
    }
    public User GetUserByOpenIdUrl(string openIdUrl)
    {
        throw new NotImplementedException();
    }
    public IList&amp;lt;Task&amp;gt; GetRecentTasks(IEnumerable&amp;lt;string&amp;gt; includeList)
    {
        throw new NotImplementedException();
    }
    public Task AddTask(Task task)
    {
        throw new NotImplementedException();
    }
    public User GetUserById(long id)
    {
        User user = this.CreateDummyUser();
        user.Id = id;

        return user;
    }
    public User SaveUser(User user)
    {
        throw new NotImplementedException();
    }
    public Task GetTaskById(long id)
    {
        throw new NotImplementedException();
    }
}&lt;/pre&gt;
&lt;p&gt;
Take notice of the methods which just throw a &lt;a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx"&gt;NotImplementedException&lt;/a&gt;,
these are methods that I just added to the interface and haven’t yet written test
cases for. (Yeah I know I’m not following true TDD, but I never claimed to be either).
Now you can compare that to these methods which use moq to create the mock.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private Mock&amp;lt;IModelContext&amp;gt; CreateMockModelContext()
{
    var context = new Mock&amp;lt;IModelContext&amp;gt;();

    context.Setup(c =&amp;gt; c.CreateUser(It.IsAny&amp;lt;User&amp;gt;()))
        .Returns&amp;lt;User&amp;gt;(user =&amp;gt;
        {
            if (user.Id &amp;lt;= 0)
            {
                user.Id = 1;
            }
            return user;
        });

    context.Setup(c =&amp;gt; c.GetUserByEmail(It.IsAny&amp;lt;string&amp;gt;()))
        .Returns&amp;lt;string&amp;gt;(email =&amp;gt;
            {
                if (email == null) { throw new ArgumentNullException(&amp;quot;email&amp;quot;); }

                User user = this.CreateDummyUser();
                user.Email = email;

                return user;
            }); ;

    context.Setup(c =&amp;gt; c.GetUserById(It.IsAny&amp;lt;long&amp;gt;()))
        .Returns&amp;lt;long&amp;gt;(id =&amp;gt; 
        {
            User user = new User();
            user.Id = id;
            return user;
        });

    context.Setup(c =&amp;gt; c.GetRecentTasks())
        .Returns(() =&amp;gt;
        {
            IList&amp;lt;Task&amp;gt; tasks = new List&amp;lt;Task&amp;gt;()
            {
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description =&amp;quot;Description 01 here&amp;quot;,
                    Headline=&amp;quot;Headline 01 here&amp;quot;,
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = &amp;quot;Name here&amp;quot;,
                    NumViews = 3,
                    Script = @&amp;quot;&amp;lt;ScriptHere&amp;gt;script&amp;lt;/ScriptHere&amp;gt;&amp;quot;,
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email =&amp;quot;one@hotmail.com&amp;quot;,
                        FirstName=&amp;quot;First&amp;quot;,
                        Id=2,
                        LastName=&amp;quot;Last&amp;quot;,
                        MiddleName=&amp;quot;Middle&amp;quot;,
                    }
                },
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description =&amp;quot;Description 02 here&amp;quot;,
                    Headline=&amp;quot;Headline 02 here&amp;quot;,
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = &amp;quot;Name here&amp;quot;,
                    NumViews = 3,
                    Script = @&amp;quot;&amp;lt;ScriptHere&amp;gt;script2&amp;lt;/ScriptHere&amp;gt;&amp;quot;,
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email =&amp;quot;one@hotmail.com&amp;quot;,
                        FirstName=&amp;quot;First&amp;quot;,
                        Id=2,
                        LastName=&amp;quot;Last&amp;quot;,
                        MiddleName=&amp;quot;Middle&amp;quot;,
                    }
                }

            };
            return tasks;
        });

    return context;
}
protected internal User CreateDummyUser()
{
    User user = new User()
    {
        Email = &amp;quot;email&amp;quot;,
        FirstName = &amp;quot;First&amp;quot;,
        LastName = &amp;quot;Last&amp;quot;,
        MiddleName = &amp;quot;Middle&amp;quot;
    };

    return user;
}&lt;/pre&gt;
&lt;p&gt;
Since I’m just mocking methods all I’m really doing here is using the moq &lt;a href="http://www.clariusconsulting.net/labs/moq/html/3BFDD309.htm"&gt;Setup&lt;/a&gt; method
(formerly known as Expect), and the &lt;a href="http://www.clariusconsulting.net/labs/moq/html/312A14EA.htm"&gt;Returns&lt;/a&gt; method
to implement the behavior that I needed. The key to note here is that if you need
to access the parameter(s) passed into the method, then you will have to used Returns
and pass in a lambda expression that contains the behavior. In that lamdba you can
name the parameter anything you want, but I would suggest you name it the same name
that the method you are mocking names it. This makes it much more understandable what
you are actually doing.
&lt;/p&gt;
&lt;p&gt;
Sayed Ibrahim Hashimi
&lt;/p&gt;</description>
      <comments>http://sedodream.com/CommentView,guid,e2d2acfd-8a99-42b3-99ff-de085619ce51.aspx</comments>
      <category>mocks</category>
      <category>moq</category>
      <category>unit testing</category>
    </item>
  </channel>
</rss>