<?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>Lesnikowski Blog &#187; UnitTesting</title>
	<atom:link href="http://www.lesnikowski.com/blog/index.php/tag/unittesting/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lesnikowski.com/blog</link>
	<description>.Net</description>
	<lastBuildDate>Wed, 28 Jul 2010 10:10:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Testing DateTime.Now</title>
		<link>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=testing-datetime-now</link>
		<comments>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:07:18 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=480</guid>
		<description><![CDATA[
When you are doing Test Driven Development (TDD) many time during the testing phase you&#8217;ll find yourself with a code that depends on current time.
It&#8217;s not possible write tests for this code as DateTime.Now changes constantly.
Let&#8217;s take a look at following method:

public string CreateName(...)
{
   return &#34;name &#34; + DateTime.Now;
}

The solution to this problem [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-486" title="clock" src="http://www.lesnikowski.com/blog/wp-content/uploads/2010/01/clock.jpg" alt="" width="211" height="142" /></p>
<p>When you are doing Test Driven Development (TDD) many time during the testing phase you&#8217;ll find yourself with a code that depends on current time.</p>
<p>It&#8217;s not possible write tests for this code as <strong>DateTime.Now changes constantly</strong>.</p>
<p>Let&#8217;s take a look at following method:</p>
<pre class="brush: csharp;">
public string CreateName(...)
{
   return &quot;name &quot; + DateTime.Now;
}
</pre>
<p>The solution to this problem is simple. We&#8217;ll introduce <em>Clock</em> class with the same interface as <em>DateTime</em>:</p>
<pre class="brush: csharp;">
public string CreateName(...)
{
   return &quot;name &quot; + Clock.Now;
}
</pre>
<p>We&#8217;d like the test to look something like this:</p>
<pre class="brush: csharp;">
[Test]
public void CreateName_AddsCurrentTimeAtEnd()
{
    using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))
    {
        string name = new ReportNameService().CreateName(...);
        Assert.AreEqual(&quot;name 2010-12-31 23:59:00&quot;, name);
    }
}
</pre>
<p><strong>Tests should not leave any side effects</strong>. This is why we are using IDisposable pattern. After text execution <em>Clock.Now</em> is reverted and again returns current time.</p>
<p>Finally this is how <em>Clock</em> class looks like:</p>
<pre class="brush: csharp;">
public class Clock : IDisposable
{
    private static DateTime? _nowForTest;

    public static DateTime Now
    {
        get { return _nowForTest ?? DateTime.Now; }
    }

    public static IDisposable NowIs(DateTime dateTime)
    {
        _nowForTest = dateTime;
        return new Clock();
    }

    public void Dispose()
    {
        _nowForTest = null;
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Programmatically check Log4Net log</title>
		<link>http://www.lesnikowski.com/blog/index.php/programmatically-check-log4net/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=programmatically-check-log4net</link>
		<comments>http://www.lesnikowski.com/blog/index.php/programmatically-check-log4net/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 10:16:49 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[log4net]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=308</guid>
		<description><![CDATA[Today I needed to create unit test that checked if the NHibernate query was generated optimally.
Good thing is that, in case of an inefficient query, NHibernate puts a warning using log4net:

log.Warn( &#34;firstResult/maxResults specified with collection fetch; applying in memory!&#34; );

I wanted something like this:

[Test]
public void FindUsersBy_QueryWithLimit_LimitsOnSQLSide()
{
    using (LogChecker logChecker
    [...]]]></description>
			<content:encoded><![CDATA[<p>Today I needed to create unit test that checked if the NHibernate query was generated optimally.</p>
<p>Good thing is that, in case of an inefficient query, NHibernate puts a warning using log4net:</p>
<pre class="brush: csharp;">
log.Warn( &quot;firstResult/maxResults specified with collection fetch; applying in memory!&quot; );
</pre>
<p>I wanted something like this:</p>
<pre class="brush: csharp;">
[Test]
public void FindUsersBy_QueryWithLimit_LimitsOnSQLSide()
{
    using (LogChecker logChecker
        = new LogChecker(&quot;NHibernate&quot;, Level.Warn))
    {
        // Execute query using NHibernate

        // ....

        Assert.IsEmpty(logChecker.Messages);
    }
}
</pre>
<p>The problem is that it&#8217;s not that easy to attach MemoryAppender for a duration of unit test to the specified logger.</p>
<p>Anyway here&#8217;s the code:</p>
<pre class="brush: csharp;">
public class LogChecker : IDisposable
{
    readonly Logger _logger;
    readonly Level _previousLevel;
    readonly MemoryAppender _appender = new MemoryAppender();

    public LogChecker(string logName, Level levelToCheck)
    {
        _logger = (Logger)LogManager.GetLogger(logName).Logger;
        _logger.AddAppender(_appender);
        _previousLevel = _logger.Level;
        _logger.Level = levelToCheck;
    }

    public List&lt;string&gt; Messages
    {
        get
        {
            return new List&lt;LoggingEvent&gt;(_appender.GetEvents())
                  .ConvertAll(x =&gt; x.RenderedMessage);
        }
    }

    public void Dispose()
    {
        _logger.Level = _previousLevel;
        _logger.RemoveAppender(_appender);
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/programmatically-check-log4net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit testing is good</title>
		<link>http://www.lesnikowski.com/blog/index.php/unit-testing-is-good/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=unit-testing-is-good</link>
		<comments>http://www.lesnikowski.com/blog/index.php/unit-testing-is-good/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 07:20:46 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=200</guid>
		<description><![CDATA[Recently Ayende added another spot-the-bug post. Usually I&#8217;m just curious how fast people find the problem.
Some time ago he also published few posts about how he does unit testing.
In &#8220;Scenario driven tests&#8221; he says that, as I understand it, it&#8217;s better to test a whole scenario not a single method. I&#8217;m okay with that, as [...]]]></description>
			<content:encoded><![CDATA[<p>Recently Ayende added another <a href="http://ayende.com/Blog/archive/2009/10/21/challenge-can-you-spot-the-bug.aspx">spot-the-bug post</a>. Usually I&#8217;m just curious how fast people find the problem.</p>
<p>Some time ago he also published few posts about how he does unit testing.</p>
<p>In <a href="http://ayende.com/Blog/archive/2009/09/29/scenario-driven-tests.aspx">&#8220;Scenario driven tests&#8221;</a> he says that, as I understand it, it&#8217;s better to <strong>test a whole scenario</strong> not a single method. I&#8217;m okay with that, as long as scenarios are in <strong>reasonable numbers</strong> and <strong>code coverage is high</strong>.</p>
<p>In <a href="http://ayende.com/Blog/archive/2009/09/28/even-tests-has-got-to-justify-themselves.aspx">&#8220;Tests have got to justify themselves&#8221;</a> he states <strong>&#8220;I am not using TDD.&#8221;</strong></p>
<p>Well if you were you would not have so many problems in 10 lines of code, period.<br />
You want to test scenarios ok, but when you&#8217;ve simple method with lots of logic, <strong>you are going to make a mistake at some point</strong>. Test it!</p>
<pre class="brush: csharp;">
public static string FirstCharacters(this string self, int numOfChars)
{
    if (self == null)
        return &quot;&quot;;
    if (self.Length &lt; numOfChars)
        return self;
    return self
        .Replace(Environment.NewLine, &quot; &quot;)
        .Substring(0, numOfChars - 3) + &quot;...&quot;;
}
</pre>
<p>Each of the following tests will fail:<br />
(negative values are not reasonable input for such method, so we won&#8217;t go there)</p>
<pre class="brush: csharp;">
[Test]
public void FirstCharacters_EmptyString_Truncates()
{
    Assert.AreEqual(&quot;&quot;, &quot;&quot;.FirstCharacters(0));
}

[Test]
public void FirstCharacters_RegularString_Truncates()
{
    Assert.AreEqual(&quot;12345&quot;, &quot;12345&quot;.FirstCharacters(5));
}

[Test]
public void Method_Condition_Result()
{
    Assert.AreEqual(&quot;...&quot;, &quot;12345&quot;.FirstCharacters(2));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates()
{
    Assert.AreEqual(&quot;  &quot;, &quot;\r\n\r\n\r\n&quot;.FirstCharacters(2));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates2()
{
    Assert.AreEqual(&quot; ...&quot;, &quot;\n\n\n\n\n\n\n\n&quot;.FirstCharacters(4));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates3()
{
    Assert.AreEqual(&quot;start end&quot;, &quot;start\nend&quot;.FirstCharacters(255));
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/unit-testing-is-good/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to test email sending?</title>
		<link>http://www.lesnikowski.com/blog/index.php/how-to-test-email-sending/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=how-to-test-email-sending</link>
		<comments>http://www.lesnikowski.com/blog/index.php/how-to-test-email-sending/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 08:11:13 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=94</guid>
		<description><![CDATA[Nearly every web application these days sends some notifications to its users.
Many times before, I came across people who said that it&#8217;s not possible to test such things.
Well, they are wrong!
There is a very cool project on sourceforge called nDumbster:
http://ndumbster.sourceforge.net
nDumbster is a simple fake SMTP server designed especially to enable unit testing.

[TestFixture]
public class SmtpClientTest
{
  [...]]]></description>
			<content:encoded><![CDATA[<p>Nearly every web application these days sends some notifications to its users.</p>
<p>Many times before, I came across people who said that it&#8217;s not possible to test such things.<br />
Well, they are wrong!</p>
<p>There is a very cool project on sourceforge called <strong>nDumbster</strong>:<br />
<a href="http://ndumbster.sourceforge.net">http://ndumbster.sourceforge.net</a></p>
<p>nDumbster is a simple fake SMTP server designed especially to enable unit testing.</p>
<pre class="brush: csharp;">
[TestFixture]
public class SmtpClientTest
{
    private const int _port = 25;
    private SimpleSmtpServer _smtpServer;

    [SetUp]
    public void SetUp()
    {
        _smtpServer = SimpleSmtpServer.Start(_port);
    }

    [TearDown]
    public void TearDown()
    {
        _smtpServer.Stop();
    }

    [Test]
    public void SendMessage_SendsMessage()
    {
        Mail.Text(&amp;quot;Some text&amp;quot;)
            .Subject(&amp;quot;Some subject&amp;quot;)
            .From(new MailBox(&amp;quot;alice@mail.com&amp;quot;, &amp;quot;Alice&amp;quot;))
            .To(new MailBox(&amp;quot;bob@mail.com&amp;quot;, &amp;quot;Bob&amp;quot;))
            .UsingNewSmtp()
            .Server(&amp;quot;localhost&amp;quot;)
            .OnPort(_port)
            .Send();

        Assert.AreEqual(1, _smtpServer.ReceivedEmailCount);
        SmtpMessage mail = _smtpServer.ReceivedEmail[0];
        Assert.AreEqual(&amp;quot;\&amp;quot;Alice\&amp;quot; &amp;lt;alice@mail.com&amp;gt;&amp;quot;, mail.Headers[&amp;quot;From&amp;quot;]);
        Assert.AreEqual(&amp;quot;\&amp;quot;Bob\&amp;quot; &amp;lt;bob@mail.com&amp;gt;&amp;quot;, mail.Headers[&amp;quot;To&amp;quot;]);
        Assert.AreEqual(&amp;quot;Some subject&amp;quot;, mail.Headers[&amp;quot;Subject&amp;quot;]);
        Assert.AreEqual(&amp;quot;Some text&amp;quot;, mail.Body);
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/how-to-test-email-sending/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GoToTest macro for VisualStudio</title>
		<link>http://www.lesnikowski.com/blog/index.php/gototest-macro-for-visualstudio/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=gototest-macro-for-visualstudio</link>
		<comments>http://www.lesnikowski.com/blog/index.php/gototest-macro-for-visualstudio/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 08:32:35 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=73</guid>
		<description><![CDATA[
If you are using Visual Studio 2010 Navigate To Test Extension might be a better choice for you.
When you are doing Test Driven Development (TDD) you are constantly switching back and forth between production code and test classes.
As it&#8217;s good idea to have those files in separate projects, it&#8217;s sometimes very hard to find test [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/4.png" alt="4" title="4" width="392" height="77" class="alignnone size-full wp-image-77" /></p>
<p>If you are using Visual Studio 2010 <a href="http://www.lesnikowski.com/blog/index.php/navigate-to-test-visual-studio-extension/">Navigate To Test Extension</a> might be a better choice for you.</p>
<p>When you are doing Test Driven Development (TDD) you are <strong>constantly switching back and forth</strong> between production code and test classes.</p>
<p>As it&#8217;s good idea to have those files in separate projects, it&#8217;s sometimes very hard to find test code for a class and vice-versa.</p>
<p>Some time ago I decided to write a simple <strong>Visual Studio macro</strong>, that solves this problem.<br />
It&#8217;s based on the convention that all your test classes have Test or Tests suffix (e.g. CSVReader.cs and CSVReaderTests.cs)</p>
<p>I&#8217;m far from being VB expert, so the code is not perfect (Why does VS use Visual Basic for Macros?):</p>
<pre class="brush: vb;">
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.IO

Public Module MainModule
    Dim _patterns As String() = {&quot;{0}Test&quot;, &quot;{0}Tests&quot;}
    Dim _reversePatterns As String() = {&quot;Tests&quot;, &quot;Test&quot;}

    Sub GoToTest()
        If DTE.SelectedItems.Count = 0 Then
            Return
        End If

        Dim fullFileName As String = DTE.ActiveDocument.Name
        Dim fileName As String = Path.GetFileNameWithoutExtension(fullFileName)
        Dim extension As String = Path.GetExtension(fullFileName)

        If IsTestFile(fileName) Then
            For Each reversePattern As String In _reversePatterns
                If fileName.Contains(reversePattern) Then
                    TryOpen(fileName.Replace(reversePattern, &quot;&quot;) + extension)
                End If
            Next
        Else
            For Each pattern As String In _patterns
                TryOpen(String.Format(pattern, fileName) + extension)
            Next pattern
        End If
    End Sub

    Function IsTestFile(ByVal fileName As String)
        For Each reversePattern As String In _reversePatterns
            If fileName.Contains(reversePattern) Then Return True
        Next
        Return False
    End Function

    Function TryOpen(ByVal fileName As String) As Boolean
        Dim item As EnvDTE.ProjectItem
        item = FindItem(FileName)
        If Not (item Is Nothing) Then
            OpenItem(item)
            Return True
        End If
        Return False
    End Function

    Function FindItem(ByVal fileName As String) As EnvDTE.ProjectItem
        If String.IsNullOrEmpty(fileName) Then
            Return Nothing
        End If
        Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(fileName)
        Return item
    End Function

    Sub OpenItem(ByVal item As EnvDTE.ProjectItem)
        item.Open()
        item.Document.Activate()
    End Sub

End Module
</pre>
<p><strong>How to install:</strong></p>
<p>Start Visual Studio and go to Tools/Macros/Load Macro Project&#8230;:<br />
<a href="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/1.png"><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/1-150x150.png" alt="1" title="1" width="150" height="150" class="size-thumbnail wp-image-74" /></a></p>
<p>Right click on the Visual Studio toolbar, and select customize:<br />
<a href="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/2.png"><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/2-150x150.png" alt="2" title="2" width="150" height="150" class="size-thumbnail wp-image-74" /></a></p>
<p>Select &#8216;Macros&#8217; category and find &#8216;GoToTest&#8217; Macro:<br />
<a href="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/3.png"><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/3-150x150.png" alt="3" title="3" width="150" height="150" class="size-thumbnail wp-image-74" /></a></p>
<p>Of course you can change the name of the button.<br />
<img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/4.png" alt="4" title="4" width="392" height="77" class="alignnone size-full wp-image-77" /></p>
<p>And finally the macro itself:<br />
<a href='http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/GotoTestMacro.vsmacros'>GotoTestMacro</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/gototest-macro-for-visualstudio/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My ReSharper templates for Unit Testing</title>
		<link>http://www.lesnikowski.com/blog/index.php/my-resharper-templates-for-unit-testing/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=my-resharper-templates-for-unit-testing</link>
		<comments>http://www.lesnikowski.com/blog/index.php/my-resharper-templates-for-unit-testing/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 07:56:31 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=64</guid>
		<description><![CDATA[As I always have problem synchronizing my office and home machine&#8217;s templates I thought this would be good place to store them.
Inline templates (LiveTemplates.xml)
test

[Test]
public void Method_Condition_Result()
{
	$END$
}

setup

[SetUp]
public void SetUp()
{
	$END$
}

record

using(mocks.Record())
{
	$END$
}

play

using(mocks.Playback())
{
	$END$
}

File templates (FileTemplates.xml)
NUnitTestFile

using NUnit.Framework;

namespace $Namespace$
{
    [TestFixture]
    public class $FileName$
    {
        [Test]
  [...]]]></description>
			<content:encoded><![CDATA[<p>As I always have problem synchronizing my office and home machine&#8217;s templates I thought this would be good place to store them.</p>
<h3>Inline templates (LiveTemplates.xml)</h3>
<p><strong>test</strong></p>
<pre class="brush: csharp;">
[Test]
public void Method_Condition_Result()
{
	$END$
}
</pre>
<p><strong>setup</strong></p>
<pre class="brush: csharp;">
[SetUp]
public void SetUp()
{
	$END$
}
</pre>
<p><strong>record</strong></p>
<pre class="brush: csharp;">
using(mocks.Record())
{
	$END$
}
</pre>
<p><strong>play</strong></p>
<pre class="brush: csharp;">
using(mocks.Playback())
{
	$END$
}
</pre>
<h3>File templates (FileTemplates.xml)</h3>
<p><strong>NUnitTestFile</strong></p>
<pre class="brush: csharp;">
using NUnit.Framework;

namespace $Namespace$
{
    [TestFixture]
    public class $FileName$
    {
        [Test]
        public void Method_Condition_Result()
        {
        }
    };
}
</pre>
<p><a href='http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/FileTemplates.xml'>FileTemplates</a><br />
<a href='http://www.lesnikowski.com/blog/wp-content/uploads/2009/09/LiveTemplates.xml'>LiveTemplates</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/my-resharper-templates-for-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
