<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Quickduck &#187; Rhino</title>
	<atom:link href="http://quickduck.com/blog/tag/rhino/feed/" rel="self" type="application/rss+xml" />
	<link>http://quickduck.com/blog</link>
	<description>Straight from the mind of geniuseseses....</description>
	<lastBuildDate>Wed, 30 Jun 2010 10:52:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Unit Testing DateTime.Now</title>
		<link>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/</link>
		<comments>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 11:54:45 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=138</guid>
		<description><![CDATA[I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it. Consider the follow code: public class MyEntity { public DateTime Created { get; set; } } public class MyRepository { [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it.</p>
<p>Consider the follow code:</p>
<pre class="brush: csharp;">public class MyEntity
 {
   public DateTime Created { get; set; }
 }

 public class MyRepository
 {
   public void UpdateMyEntity(MyEntity entity)
   {
     entity.Created = DateTime.Now;
   }
 }</pre>
<p>Unless you are one of one of those fancy pants with <a title="TypeMock" href="http://www.typemock.com/" target="_blank">TypeMock</a> and the ability to <a title="Typemock Isolator 5.3.1 can fake DateTime.Now" href="http://bloggingabout.net/blogs/dennis/archive/2009/06/03/typemock-isolator-5-3-1-can-fake-datetime-now.aspx" target="_blank">fake DateTime.Now</a>, the rest of use must look elsewhere for a solution. Here are three different ways to solve this.</p>
<p><strong>1. Wrap your DateTime calls with another class</strong></p>
<p><a title="Dealing with time in tests" href="http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" target="_blank">Some people</a> prefer using a static &#8220;Clock&#8221; class to handle this which can be easily faked out during your unit testing.</p>
<pre class="brush: csharp;">
public static class Clock
{
    public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;
}
</pre>
<p>This approach, while decoupling your dependency on System.DateTime is a bit of overkill and requires all developers on the project to be aware of it and to use it.</p>
<p><strong>2.Use an Interface and your favourite Isolation Framework</strong><span> </span></p>
<pre class="brush: csharp;">
public interface IClock
{
  DateTime Now {get;}
}

public class SystemClock : IClock
{
  public DateTime Now { get { return DateTime.Now; } }
}
</pre>
<p>You can now use an isolation framework such as <a title="Rhino Mocks" href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino.Mocks</a> to fake the call to Now();</p>
<p><strong>3. Use a DateTime Comparer that accepts a range</strong></p>
<p>While not 100% accurate to the millisecond, this approach is my prefered approach as you don&#8217;t have to change to your code just to unit test it. No littering your code with IClock dependencies or using a delegate to return the current DateTime.Now (although one could argue that DateTime.Now <a title="Properties vs Methods" href="http://msdn.microsoft.com/en-us/library/bzwdh01d%28VS.71%29.aspx#cpconpropertyusageguidelinesanchor1" target="_blank">shouldn&#8217;t be a property</a> to begin with). This approach asserts that the Created property that is set in MyRepository.Update is within a certain range.</p>
<pre class="brush: csharp;">
 /// &lt;summary&gt;
 /// Helper class to compare 2 values are within a certain range.
 /// &lt;/summary&gt;
 public class DateComparer : IComparer&lt;DateTime&gt;
 {
 public TimeSpan MarginOfError { get; private set; }

 public DateComparer(TimeSpan marginOfError)
 {
   MarginOfError = marginOfError;
 }

  public int Compare(DateTime x, DateTime y)  // x = expected, y = actual
   {
     var margin = x - y;
     if (margin &lt;= MarginOfError)
       return 0;
     return new Comparer(CultureInfo.CurrentUICulture).Compare(x, y);
   }
 }
</pre>
<p>You can now write the follow test:</p>
<pre class="brush: csharp;">
public void MyRepository_UpdateTest()
 {
   var repository = new MyRepository();
   var entity = new MyEntity();
   repository.UpdateMyEntity(entity);
   var comparer = new DateComparer(new TimeSpan(0, 0, 0, 5));
   Assert.IsTrue(comparer.Compare(entity.Created, DateTime.Now) == 0);
 }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Expression Tree Equality</title>
		<link>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/</link>
		<comments>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 03:31:02 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Comparison]]></category>
		<category><![CDATA[Equality]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=131</guid>
		<description><![CDATA[Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result. This method will fail [TestMethod] public void TestDoesNotWork() { Expression&#60;Func&#60;int, int&#62;&#62; expressionA = x =&#62; x + 1; Expression&#60;Func&#60;int, int&#62;&#62; expressionB = x =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.</p>
<p><strong>This method will fail</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesNotWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA, expressionB);
}
</pre>
<p>This looks like it should work however it doesn&#8217;t. This is because when using anonymous expressions/delegates the CLR does some magic behind the scene to add a method on the fly, creating a new instance for every anonymous expression/delegate.</p>
<p>So if you have two expressions that are syntactically the same but not the same reference the easiest way to ensure they are the same is to compile the expression and invoke it comparing the resultant value.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA.Compile().Invoke(3), expressionB.Compile().Invoke(3));
}
</pre>
<p>An alternate approach would be to de-construct each constituent part of the expression trees comparing each part as you go. This however is far more complex.</p>
<p>For a more real world example that involves using Rhino mocks and Expect calls please read on:</p>
<p><span id="more-131"></span></p>
<p>When using Rhino Mocks and setting up an Expect call on a method that takes an expression you will most likely find that the Expect assertion always fails.</p>
<p><strong> The class that will be mocked out.</strong><br />
This class will have the method on it that takes an expression.</p>
<pre class="brush: csharp;">
public class Repository
{
  public virtual void Get&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition)
  {
        // Actual logic.
   }
}
</pre>
<p><strong>The class we are unit testing</strong></p>
<pre class="brush: csharp;">
public class UserManager
{
  public Repository Repo { get; set; }

  public void GetUserById(int id)
  {
    Repo.Get&lt;User&gt;(x =&gt; x.Id == id);
  }
}
</pre>
<p><strong>Supporting classes</strong></p>
<pre class="brush: csharp;">
public class User
{
  public int Id { get; set;  }
  public int Name { get; set; }
}
</pre>
<p>For our unit test we want to test that when we call the GetUserById() method on the UserManager class that we Expect the Repository.Get<TEntity>() method will be called with an expected expression value.</p>
<p><strong>Unit Test</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void Test()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };
  manager.Repo.Expect(r =&gt; r.Get&lt;User&gt;(x =&gt; x.Id == 3));

  // Act
  manager.GetUserById(3);

  // Assert
  manager.Repo.VerifyAllExpectations();
}
</pre>
<p>This looks like it should work however it won&#8217;t.</p>
<p>So using the approach listed earlier we can test that the method with an expression is called with the correct value by compiling and invoking the expected expression and the actual expression that was called and comparing their values.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestExpressionCalled()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };

  // Act
  manager.GetUserById(3);

  // Assert
  Expression&lt;Func&lt;User, bool&gt;&gt; expected = x =&gt; x.Id == 3;
  Expression&lt;Func&lt;User, bool&gt;&gt; actual = (Expression&lt;Func&lt;User, bool&gt;&gt;)manager.Repo.GetArgumentsForCallsMadeOn(r =&gt; r.Get&lt;User&gt;(null))[0][0];

  User user = new User { Id = 3 };
  Assert.AreEqual(expected.Compile().Invoke(user), actual.Compile().Invoke(user));
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
