<?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>Arrange Act Assert &#187; Unit tests</title> <atom:link href="http://www.arrangeactassert.com/category/unit-tests/feed/" rel="self" type="application/rss+xml" /><link>http://www.arrangeactassert.com</link> <description>Jag Reehal on Agile Development, ASP.NET MVC and all manner of good stuff</description> <lastBuildDate>Thu, 24 Nov 2011 00:01:20 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /> <item><title>Code First Entity Framework Unit Test Examples</title><link>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/</link> <comments>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/#comments</comments> <pubDate>Wed, 28 Jul 2010 00:47:07 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Entity Framework]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1072</guid> <description><![CDATA[Following the release of the Entity Framework 4 CTP 4 and Scott Gu’s excellent blog post about Code-First Development with Entity Framework 4, we&#8217;ll be having a look at what your Code-First Entity Framework unit tests might look like. The code used in this post is available here. Remember in order to run the code [...]]]></description> <content:encoded><![CDATA[<p>Following the release of the <a
href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4announcement.aspx">Entity Framework 4 CTP 4</a> and <a
href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx">Scott Gu’s excellent blog post about Code-First Development with Entity Framework 4</a>, we&#8217;ll be having a look at what your Code-First Entity Framework unit tests might look like.</p><p>The code used in this post is available <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/UnitTestingCodeFirstDevelopmentWithEF4.zip">here</a>.</p><p>Remember in order to run the code or to create unit tests shown in this post you need to download and install:</p><ul><li><a
href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4e094902-aeff-4ee2-a12d-5881d4b0dd3e&#038;displaylang=en">Microsoft ADO.NET Entity Framework Feature Community Technology Preview 4</a></li><li> <a
href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0d2357ea-324f-46fd-88fc-7364c80e4fdb&#038;displaylang=en">Microsoft SQL Server Compact 4.0 Community Technology Preview for Windows Desktop</a></li></ul><h3 class="subheading">Getting started</h3><p>The entities we will be using are the same Dinner and RSVP entities Scott used in his post</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Dinner
{
    public int DinnerID { get; set; }
    public string Title { get; set; }
    public DateTime EventDate { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
    public string HostedBy { get; set; }

    public virtual ICollection&lt;RSVP&gt; RSVPs { get; set; }
}

public class RSVP
{
    public int RsvpID { get; set; }
    public int DinnerID { get; set; }
    public string AtendeeEmail { get; set; }

    public virtual Dinner Dinner { get; set; }
}
</pre><p>as well as the NerdDinners class which inherits from DbContext</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class NerdDinners : DbContext
{
    public DbSet&lt;Dinner&gt; Dinners { get; set; }
    public DbSet&lt;RSVP&gt; RSVP { get; set; }
}
</pre><h3 class="subheading">Creating Entity Framework Code-First Unit Tests</h3><p>So let’s start off by writing a test to check a Dinner can be saved in the database.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_be_able_to_save_new_dinner()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    NerdDinners nerdDinners = new NerdDinners();

    Dinner dinner = new Dinner
                        {
                            Title = &quot;Dinner with the Queen&quot;,
                            Address = &quot;Buckingham Palace&quot;,
                            EventDate = DateTime.Now,
                            HostedBy = &quot;Liz and Phil&quot;,
                            Country = &quot;England&quot;
                        };

    nerdDinners.Dinners.Add(dinner);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    Dinner savedDinner = (from d in nerdDinners.Dinners
                            where d.DinnerID == dinner.DinnerID
                            select d).Single();

    savedDinner.Title.ShouldEqual(dinner.Title);
    savedDinner.Address.ShouldEqual(dinner.Address);
    savedDinner.EventDate.ShouldEqual(dinner.EventDate);
    savedDinner.HostedBy.ShouldEqual(dinner.HostedBy);
    savedDinner.Country.ShouldEqual(dinner.Country);
}
</pre><p>There are a couple of things to note here.</p><p>In the LINQ query to get the saved Dinner from the database we can use the ID of the Dinner we created because when you call the SaveChanges() method the Entity Framework will set the identity value of the object(s) being persisted.</p><p>The other thing we could have done is use a &#8216;domain signature&#8217; to check for equality, but that’s for a future blog post.</p><h3 class="subheading">Testing entities with foreign keys</h3><p>The code below shows a test for saving an RSVP.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_be_able_to_save_new_rsvp()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    NerdDinners nerdDinners = new NerdDinners();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    Dinner dinner = new Dinner
                        {
                            Title = &quot;Dinner with the Queen&quot;,
                            Address = &quot;Buckingham Palace&quot;,
                            EventDate = DateTime.Now,
                            HostedBy = &quot;Liz and Phil&quot;,
                            Country = &quot;England&quot;
                        };
    rsvp.Dinner = dinner;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.AtendeeEmail.ShouldEqual(rsvp.AtendeeEmail);
}
</pre><p>One thing you might have noticed here is that we had to create a Dinner as well as an RSVP.  This is because of the foreign key constraint for the DinnerID.</p><p>So at this point you could be asking why we can&#8217;t use the Dinner we created in the first test?  The trouble, danger and bad practice of doing that is falling into the trap of creating a dependency of your tests running in some sort of order or sequence.</p><h3 class="subheading">AlwaysRecreateDatabase</h3><p>In his post Scott created a NerdDinnersInitializer class which inherited from RecreateDatabaseIfModelChanges.  But this is not good enough for a unit test because we need to ensure each test starts off in a known state.</p><p>This doesn’t mean we have to create a Dinner each time we want to save an RSVP because we can create an NerdDinnersInitializer which is already populated with a dinner by overriding the Seed method.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class NerdDinnersInitializer : AlwaysRecreateDatabase&lt;NerdDinners&gt;
{
    protected override void Seed(NerdDinners context)
    {
        var dinners = new List&lt;Dinner&gt; { new Dinner()
                                                {
                                                    Title = &quot;Dinner with the Queen&quot;,
                                                    Address = &quot;Buckingham Palace&quot;,
                                                    EventDate = DateTime.Now,
                                                    HostedBy = &quot;Liz and Phil&quot;,
                                                    Country = &quot;England&quot;
                                                }
        };
        dinners.ForEach(d =&gt; context.Dinners.Add(d));
    }
}
</pre><p>And use it in a test to check we can create an RSVP</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_be_able_to_save_new_rsvp_using_existing_dinner()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    Database.SetInitializer&lt;NerdDinners&gt;(new NerdDinnersInitializer());
    NerdDinners nerdDinners = new NerdDinners();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    rsvp.DinnerID = nerdDinners.Dinners.First().DinnerID;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.AtendeeEmail.ShouldEqual(rsvp.AtendeeEmail);
}
</pre><h3 class="subheading">The disadvantage of always creating a database is the amount of time it takes to actually create the database</h3><p>So the more times you call SetInitializer in which you&#8217;re always recreating a database, the longer it will take for your tests to run.</p><p>My recommendation is to create dummy/stub dinners upfront and call SetInitializer before you run the tests.  In NUnit this is done in the TestFixtureSetUp as shown below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixtureSetUp]
public void TestFixtureSetup()
{
    Database.SetInitializer&lt;NerdDinners&gt;(new NerdDinnersInitializer());
}
</pre><h3 class="subheading">Tests to check updates</h3><p>So now you can save a Dinner, the next test you might write is to check you can update it.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_be_able_to_update_existing_dinner()
{
    // Arrange
    NerdDinners nerdDinners = new NerdDinners();

    Dinner dinner = nerdDinners.Dinners.First();
    dinner.HostedBy = &quot;Charlie and Camilla&quot;;

    // Act
    nerdDinners.SaveChanges();

    // Assert
    Dinner savedDinner = (from d in nerdDinners.Dinners
                            where d.DinnerID == dinner.DinnerID
                            select d).Single();

    savedDinner.HostedBy.ShouldEqual(dinner.HostedBy);
}
</pre><h3 class="subheading">Testing your models</h3><p>The examples in this post follow the Entity Framework convention you get out of the box.</p><p>As we have already established the property DinnerID is a foreign key in the RSVP entity.</p><p>But if you forgot to add it, the Dinner property would always be null.</p><p>The test below verifies we are able to view information about a dinner when we retrieve an RSVP from the database.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_be_able_to_view_dinner_details()
{
    // Arrange
    NerdDinners nerdDinners = new NerdDinners();
    var dinner = nerdDinners.Dinners.First();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    rsvp.DinnerID = dinner.DinnerID;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.Dinner.Title.ShouldEqual(dinner.Title);
}
</pre><h3 class="subheading">Jag Reehal’s Final Thought on ‘Examples of Code First Entity Framework Unit Tests’</h3><p>In this post I wanted to show a few examples of how you might create unit tests for your Entity Framework projects.</p><p>The ADO.NET team have really done a great job enabling developers to be able to do code-first development and allow them to move a step closer to doing test driven development using the Entity Framework.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Using INotifyDataErrorInfo for validation in MVVM with Silverlight</title><link>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/</link> <comments>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/#comments</comments> <pubDate>Thu, 15 Jul 2010 23:13:15 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=1038</guid> <description><![CDATA[In this post we will be looking at how validation can be done by implementing the INotifyDataErrorInfo interface for a calculator we have been building as part of the Silverlight refactoring series. Like the IDataErrorInfo interface, the INotifyDataErrorInfo interface gives you the ability to do validation without throwing exceptions. The full solution for this post [...]]]></description> <content:encoded><![CDATA[<p>In this post we will be looking at how validation can be done by implementing the <a
href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo%28VS.95%29.aspx">INotifyDataErrorInfo </a>interface for a calculator we have been building as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a>.</p><p>Like the <a
href="http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/">IDataErrorInfo interface</a>, the INotifyDataErrorInfo interface gives you the ability to do validation without throwing exceptions.</p><p>The full solution for this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationINotifyDataErrorInfo.zip">here</a>.</p><h3 class="subheading">Note to WPF developers &#8211; INotifyDataErrorInfo isn&#8217;t available in WPF (yet)</h3><p>But you can vote for <a
href="https://connect.microsoft.com/VisualStudio/feedback/details/568212/inotifydataerrorinfo-for-wpf">INotifyDataErrorInfo to be in a future release of WPF</a>.</p><h3 class="subheading">Pre INotifyDataErrorInfo</h3><p>As you can see in the code below we are throwing exceptions in the setters for the two values we want to add together.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string  FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
public string  SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        try
        {
            int.Parse(_secondValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><h3 class="subheading">Implementing the INotifyDataErrorInfo interface</h3><p>As we only want the calculate button to be enabled when the user has entered valid numbers to add together, we need to keep track of any validation errors.</p><p>Similar to how we have done in other posts, we will use a class for storing validation errors instead of making it the responsibility of the ViewModel.</p><p>And that class is the EntityBase class, which I borrowed from <a
href="http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/11/18/silverlight-4-rough-notes-binding-with-inotifydataerrorinfo.aspx">Mike Taulty</a>.  Cheers Mike!</p><p>The code below shows how the EntityBase class implements the ErrorsChanged event, GetErrors method and the HasErrors property defined in the INotifyDataErrorInfo interface.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class EntityBase : INotifyDataErrorInfo
{
    public event EventHandler&lt;DataErrorsChangedEventArgs&gt; ErrorsChanged;
    readonly Dictionary&lt;string, List&lt;string&gt;&gt; _currentErrors;

    public EntityBase()
    {
        _currentErrors = new Dictionary&lt;string, List&lt;string&gt;&gt;();
    }

    public IEnumerable GetErrors(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            return (_currentErrors.Values);
        }

        MakeOrCreatePropertyErrorList(propertyName);
        return _currentErrors[propertyName];
    }

    public bool HasErrors
    {
        get
        {
            return (_currentErrors.Where(c =&gt; c.Value.Count &gt; 0).Count() &gt; 0);
        }
    }

    void FireErrorsChanged(string property)
    {
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(property));
        }
    }
    public void ClearErrorFromProperty(string property)
    {
        MakeOrCreatePropertyErrorList(property);
        _currentErrors[property].Clear();
        FireErrorsChanged(property);
    }
    public void AddErrorForProperty(string property, string error)
    {
        MakeOrCreatePropertyErrorList(property);
        _currentErrors[property].Add(error);
        FireErrorsChanged(property);
    }

    void MakeOrCreatePropertyErrorList(string propertyName)
    {
        if (!_currentErrors.ContainsKey(propertyName))
        {
            _currentErrors[propertyName] = new List&lt;string&gt;();
        }
    }
}
</pre><p>The EnitityBase class can be unit tested like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_EntityBase
{
    private EntityBase _entityBase;

    [SetUp]
    public void SetUp()
    {
        _entityBase = new EntityBase();
    }

    [Test]
    public void HasErrors_should_return_true_when_errors_exist()
    {
        // Arrange
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;X&quot;);

        // Act
        var result = _entityBase.HasErrors;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void HasErrors_should_return_true_when_no_errors_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _entityBase.HasErrors;

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void Should_be_able_to_clear_error_from_property()
    {
        // Arrange
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;X&quot;);

        // Act
        _entityBase.ClearErrorFromProperty(&quot;X&quot;);
        var result = _entityBase.GetErrors(&quot;X&quot;) as List&lt;string&gt;; 

        // Assert
        result.Count().ShouldEqual(0);

    }

    [Test]
    public void Should_be_able_to_get_error_for_property()
    {
        // Arrange
        const string errorMessage = &quot;ErrorMessage&quot;;
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;ErrorMessage&quot;);

        // Act
        var result =  _entityBase.GetErrors(&quot;X&quot;) as List&lt;string&gt;;

        // Assert
        result[0].ShouldEqual(errorMessage);

    }
}
</pre><h3 class="subheading">How the ViewModel validates user input</h3><p>We need to validate the users input each time the value of a property changes.</p><p>If you have been following the series you’ll know <a
href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/">the benefits of injecting/importing a class responsible for validation</a>, the CalculatorValidator, into the ViewModel and to validate the users input.</p><p>In the code for the CalculatorValidator class, the Validate method could have returned a collection of error messages, but to keep this example simple we&#8217;ll just return the first validation error we encounter.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public ValidationResult Validate(string value)
    {
        List&lt;ValidationResult&gt; validationResults = new List&lt;ValidationResult&gt;();
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                return new ValidationResult()
                            {
                                IsValid = false,
                                ErrorMessage = calculatorValidationRule.ErrorMessage

                            };
            }
        }
        return new ValidationResult() { IsValid = true };
    }
}

public class ValidationResult
{
    public bool IsValid { get; set; }
    public string ErrorMessage { get; set; }
}
</pre><p>If you’re new to the series the validation rules for calculator are being imported by MEF. Read how and why we are doing this in the ‘<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>‘ post.</p><h3 class="subheading">Using the INotifyDataErrorInfo interface in the ViewModel</h3><p>In the code for the ViewModel shown below take note of how:</p><ul><li>the ViewModel inherits from the EntityBase class</li><li>the CheckIfNumberIsValid method is called whenever a property value changes</li><li>the INotifyDataErrorInfo HasErrors property is used to determine if the button should be enabled in the CalculatorViewModel_ErrorsChanged handler for the ErrorsChanged event. <strong>This is one of the advantages INotifyDataErrorInfo  has over IDataErrorInfo.</strong></li></ul><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export]
public class CalculatorViewModel : EntityBase, INotifyPropertyChanged
{
    private string _firstValue;
    private string _secondValue;
    private string _result;       

    private readonly ICalculator _calculator;
    private readonly RelayCommand _calculateCommand;

    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection&lt;string&gt; FirstValueErrors { get; set; }
    private readonly ICalculatorValidator _calculatorValidator;

    [ImportingConstructor]
    public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
    {
        _calculator = calculator;
        _calculatorValidator = calculatorValidator;
        _calculateCommand = new RelayCommand(Calculate) { IsEnabled = true };
        ErrorsChanged += new EventHandler&lt;DataErrorsChangedEventArgs&gt;(CalculatorViewModel_ErrorsChanged);

        _firstValue = &quot;0&quot;;
        _secondValue = &quot;0&quot;;
    }

    void CalculatorViewModel_ErrorsChanged(object sender, DataErrorsChangedEventArgs e)
    {
        _calculateCommand.IsEnabled = HasErrors == false;
    }

    public void Calculate()
    {
        Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
    }

    public string FirstValue
    {
        get { return _firstValue; }
        set
        {
            _firstValue = value;
            CheckIfNumberIsValid(&quot;FirstValue&quot;, value);
        }
    }

    public string SecondValue
    {
        get { return _secondValue; }
        set
        {
            _secondValue = value;
            CheckIfNumberIsValid(&quot;SecondValue&quot;, value);
        }
    }

    public void CheckIfNumberIsValid(string propertyName, string value)
    {
        ClearErrorFromProperty(propertyName);

        var validationResult = _calculatorValidator.Validate(value);
        if (validationResult.IsValid  == false)
        {
            AddErrorForProperty(propertyName, validationResult.ErrorMessage);
        }
        OnPropertyChanged(propertyName);
    }

    public string Result
    {
        get { return _result; }
        private set
        {
            _result = value;
            OnPropertyChanged(&quot;Result&quot;);
        }
    }

    public RelayCommand CalculateCommand
    {
        get { return _calculateCommand; }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
}
</pre><h3 class="subheading">XAML changes for INotifyDataErrorInfo</h3><p>The final change required to implement INotifyDataErrorInfo interface is to change the text box bindings and set ValidatesOnNotifyDataErrors=True</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;TextBox Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}&quot;/&gt;
&lt;TextBox Text=&quot;{Binding SecondValue, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}&quot;/&gt;
</pre><h3 class="subheading">So what have we achieved?</h3><p>In this post we have refactored the code to use the  INotifyDataErrorInfo interface and are no longer throwing exceptions to do validation.</p><p>As well as allowing you return multiple validation errors for a property, the <a
href="https://www.silverlight.net/learn/videos/all/asynchronous-data-validation/">INotifyDataErrorInfo interface can be used for asynchronous data validation as demonstrated by Jesse Liberty in this video</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Using IDataErrorInfo for validation in MVVM with Silverlight and WPF</title><link>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/#comments</comments> <pubDate>Tue, 06 Jul 2010 23:01:57 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=968</guid> <description><![CDATA[In this post we will be looking at how validation can be done by implementing the IDataErrorInfo interface for a calculator we have been building as part of the Silverlight refactoring series. The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions. The full solution for this post can be downloaded here. [...]]]></description> <content:encoded><![CDATA[<p>In this post we will be looking at how validation can be done by implementing the <a
href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx">IDataErrorInfo</a> interface for a calculator we have been building as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a>.</p><p>The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions.</p><p>The full solution for this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationIDataErrorInfo.zip">here</a>.</p><h3 class="subheading">Pre IDataErrorInfo</h3><p>As you can see in the code below we are throwing exceptions in the setters for the two values we want to add together.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string  FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
public string  SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        try
        {
            int.Parse(_secondValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><h3 class="subheading">Implementing the IDataErrorInfo interface</h3><p>The IDataErrorInfo interface consists of two properties.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
string this[string columnName] {get;}
string Error {get;}
</pre><p>For the Error property we can just return null because we don’t want to return a single error message for the entire object.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string Error
{
    get { return null; }
}
</pre><p>For the property which returns an error for a text box we <strong>could</strong> do the validation like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string this[string columnName]
{
    get
    {
        string error = null;
        switch (columnName)
        {
            case &quot;FirstValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
            case &quot;SecondValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
        }
        return error;
    }
}
</pre><p>But as we saw in a previous post <a
href="http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/">about using ValidatesOnExceptions to do validation</a> it’s much easier to write unit tests when there are separation of concerns and the ViewModel is not responsible for validation.</p><p>So this means we need to create a class for storing the validation error for each textbox</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool HasErrors()
    {
        return Errors.Count != 0;
    }
}
</pre><p>which is inherited by a CalculatorValidator class that returns a boolean value if the property value is not valid</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public bool IsPropertyValid(string propertyName, string value)
    {
        RemoveErrors(propertyName);
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return false;
            }
        }
        return true;
    }
}
</pre><p>If you’re new to the series the validation rules for calculator are being imported by MEF.  Read how and why we are doing this in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><p>Now we can inject/import the CalculatorValidator into the ViewModel and use it to validate the users input.</p><p>As we only want the user to be able to click the calculate button when the form is valid we call we the CheckIfCalculteButtonShouldBeEnabled method when a text box value has changed.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export]
public class CalculatorViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string _firstValue;
    private string _secondValue;
    private string _result;

    private readonly ICalculator _calculator;
    private readonly RelayCommand _calculateCommand;

    public event PropertyChangedEventHandler PropertyChanged;
    private readonly ICalculatorValidator _calculatorValidator;

    [ImportingConstructor]
    public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
    {
        _calculator = calculator;
        _calculatorValidator = calculatorValidator;
        _calculateCommand = new RelayCommand(Calculate) { IsEnabled = true };

        _firstValue = &quot;0&quot;;
        _secondValue = &quot;0&quot;;
    }
    public void Calculate()
    {
        Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
    }

    public string FirstValue
    {
        get { return _firstValue; }
        set
        {
            _firstValue = value;
            OnPropertyChanged(&quot;FirstValue&quot;);
        }
    }

    public string SecondValue
    {
        get { return _secondValue; }
        set
        {
            _secondValue = value;
            OnPropertyChanged(&quot;SecondValue&quot;);
        }
    }

    public void CheckIfCalculteButtonShouldBeEnabled()
    {
        _calculateCommand.IsEnabled = _calculatorValidator.HasErrors() == false;
    }

    public string Result
    {
        get { return _result; }
        private set
        {
            _result = value;
            OnPropertyChanged(&quot;Result&quot;);
        }
    }

    public RelayCommand CalculateCommand
    {
        get { return _calculateCommand; }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }

    public string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case &quot;FirstValue&quot;:
                    error = ValidateNumber(&quot;FirstValue&quot;, _firstValue);
                    break;
                case &quot;SecondValue&quot;:
                    error = ValidateNumber(&quot;SecondValue&quot;, _secondValue);
                    break;
            }

            CheckIfCalculteButtonShouldBeEnabled();
            return error;
        }
    }

    public string ValidateNumber(string propertyName, string value)
    {
        if (!_calculatorValidator.IsPropertyValid(propertyName, value))
        {
            return _calculatorValidator.GetErrorMessageForProperty(propertyName);
        }
        return null;
    }

    public string Error
    {
        get { return null; }
    }
}
</pre><p>The code below shows how we can unit test the ViewModel which implements the IDataErrorInfo interface.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void ValidateNumber_returns_null_if_value_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;,&quot;X&quot;)).Returns(true);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;,&quot;X&quot;);

        // Assert
        result.ShouldBeNull();
    }

    [Test]
    public void ValidateNumber_returns_error_message_if_value_is_not_valid()
    {
        // Arrange
        const string errorMessage = &quot;ErrorMessageText&quot;;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;, &quot;X&quot;)).Returns(false);
        _calculatorValidator.Setup(c =&gt; c.GetErrorMessageForProperty(&quot;X&quot;)).Returns(errorMessage);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;, &quot;X&quot;);

        // Assert
        result.ShouldEqual(errorMessage);
    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><p>The final change we need to make is to change the text box binding to ValidatesOnDataErrors=True in the XAML file.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;TextBox Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
&lt;TextBox Text=&quot;{Binding SecondValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
</pre><h3 class="subheading">So what have we achieved?</h3><p>In this post we have refactored the code to use the IDataErrorInfo interface and are no longer throwing exceptions to do validation.</p><p>Whether you choose to use it or not depends if you want multiple errors for a single property to be combined into a single error message.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Enabling buttons in Silverlight and WPF using MVVM and ValidatesOnExceptions</title><link>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/</link> <comments>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/#comments</comments> <pubDate>Mon, 05 Jul 2010 23:10:40 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Moq]]></category> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=957</guid> <description><![CDATA[In a previous post we saw how exceptions could be used for Silverlight validation. While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric). The code used in this post can be downloaded here. So how [...]]]></description> <content:encoded><![CDATA[<p>In a <a
href=" Validation in Silverlight and WPF using ValidatesOnExceptions">previous post we saw how exceptions</a> could be used for Silverlight validation.</p><p>While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric).</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationUsingExceptions.zip">here</a>.</p><h3 class="subheading">So how are we going to solve the problem?</h3><p>Throughout the Silverlight refactoring series I’ve tried to illustrate how important <a
href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)">SOLID design principles</a> are for having testable applications.</p><p>So if we think about the ViewModel, we need to ask ourselves if it’s the right place or should be responsible for validation?</p><p>In this case I would say no.</p><h3 class="subheading">When should the button be enabled?</h3><blockquote><p>For a calculate button to be enabled, both text boxes must contain numeric values</p></blockquote><p>This means we have to know if both text boxes are valid <strong>at the same time</strong>.  Taking a step back here, let&#8217;s think about the bigger picture.</p><p>What if there are three or four text boxes?</p><p>What we really after is a class that will be responsible for knowing if any text boxes are invalid.</p><p>This can be done by using a validation base class.</p><p>In the code below notice how the ValidationBase class <strong>doesn&#8217;t</strong> know anything about enabling or disabling the calculate button.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public bool IsPropertyValid(string propertyName)
    {
        return !Errors.ContainsKey(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool IsValid()
    {
        return Errors.Count == 0;
    }
}
</pre><p>The code below shows the unit tests for the ValidationBase class.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_ValidatiorBase
{
    private ValidationBase _validationBase;

    [SetUp]
    public void SetUp()
    {
        _validationBase = new ValidationBase();
    }

    [Test]
    public void IsValid_should_return_false_when_errors_exist()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsValid_should_return_true_when_no_errors_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void IsPropertyValid_should_return_false_if_error_exists()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsPropertyValid(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsPropertyValid_should_return_true_if_error_does_not_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsPropertyValid(&quot;X&quot;);

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void Should_be_able_to_return_message_for_error()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldEqual(&quot;message&quot;);
    }

    [Test]
    public void Should_return_null_if_message_does_not_exist_for_error()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeNull();
    }
}
</pre><h3 class="subheading">Validating the users input</h3><p>There are three outcomes when validating what the user has entered:</p><ul><li>The value is blank</li><li>The value is not a number</li><li>The value is a number</li></ul><p>All the ViewModel wants to know is if the users input is valid, choosing the appropriate error message isn&#8217;t its concern.  This means we need a class that will be responsible for validation and returning the relevant message.</p><p>For this we will use the CalculatorValidator class we created in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public void ValidateNumber(string propertyName, string value)
    {
        RemoveErrors(propertyName);

        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return;
            }
        }
    }
}
</pre><p>This is useful because if we decide to change how to validate the user&#8217;s input neither the CalculatorValidator or the ViewModel classes need to be modified.</p><h3 class="subheading">Hooking it all up</h3><p>To use the CalculatorValidator in the ViewModel it has to be injected/imported.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
{
    _calculator = calculator;
    _calculatorValidator = calculatorValidator;
    ...
}
</pre><p>Each time a user enters a value in the text boxes the CheckIfNumberIsValid method checks if the calculate button should be enabled and throws an exception if the users value is not valid.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        CheckIfNumberIsValid(&quot;FirstValue&quot;, out _firstValue, value);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        CheckIfNumberIsValid(&quot;SecondValue&quot;, out _secondValue, value);
    }
}

public void CheckIfNumberIsValid(string propertyName, out string propertyValue, string value)
{
    _calculatorValidator.ValidateNumber(propertyName, value);

    CheckIfCalculteButtonShouldBeEnabled();

    if (_calculatorValidator.IsPropertyValid(propertyName))
    {
        propertyValue = value;
        OnPropertyChanged(propertyName);
    }
    else
    {
        throw new Exception(_calculatorValidator.GetErrorMessageForProperty(propertyName));
    }
}

public void CheckIfCalculteButtonShouldBeEnabled()
{
    _calculateCommand.IsEnabled = _calculatorValidator.IsValid();
}
</pre><h3 class="subheading">Unit testing the ViewModel in MVVM</h3><p>By using <a
href="http://code.google.com/p/moq/">Moq</a> we can unit test the ViewModel to ensure the button is enabled when there are no validation errors and not enabled when there are validation errors.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    [ExpectedException(typeof(Exception))]
    public void Will_throw_exception_if_input_is_invalid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Throws(new Exception());

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;X&quot;);

        // Assert
        // should throw exception
    }

    [Test]
    public void Will_set_property_value_if_input_is_valid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Returns(true);

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;11&quot;);

        // Assert
        propertyValue.ShouldEqual(&quot;11&quot;);

    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>By using a validation base class we are able to store validation errors and can determine if the controls on the page are all valid.</p><p>The ViewModel can take advantage of this functionality and use it to enable and disable the calculate button.</p><p>Using exceptions for validation isn&#8217;t every developers cup of tea, so be sure to keep an eye on the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> to see other approaches we can take to do validation in Silverlight 4.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How to Apply the Single Responsibility Principle to View Models in Silverlight and WPF</title><link>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/#comments</comments> <pubDate>Mon, 14 Jun 2010 21:46:41 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=828</guid> <description><![CDATA[When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much. In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the Single Responsibility Principle (SRP). The code used in this post can be [...]]]></description> <content:encoded><![CDATA[<p>When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much.</p><p>In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the <a
href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle (SRP)</a>.</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorSingleResponsibilityPrinciple.zip">here</a>.</p><h3 class="subheading">Why should you care?</h3><p>Currently the ViewModel looks like this</p><pre class="brush: csharp; gutter: false; highlight: [22,23,24,25]; title: ; toolbar: true; notranslate">
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SilverlightCalculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private string _firstValue;
        private string _secondValue;
        private string _result;

        private readonly ICommand _calculateCommand;       

        public event PropertyChangedEventHandler PropertyChanged;

        public CalculatorViewModel()
        {
            _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
        }

        public void Calculate()
        {
            Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
        }

        public string FirstValue
        {
            get { return _firstValue; }
            set
            {
                _firstValue = value;
                OnPropertyChanged(&quot;FirstValue&quot;);
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                OnPropertyChanged(&quot;SecondValue&quot;);
            }
        }

        public string Result
        {
            get { return _result; }
            private set
            {
                _result = value;
                OnPropertyChanged(&quot;Result&quot;);
            }
        }

        public ICommand CalculateCommand
        {
            get { return _calculateCommand; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</pre><p>As you can see the logic to add two numbers is in the Calculate method of the ViewModel.</p><p>Therefore <strong>the ViewModel is responsible for calculating two numbers</strong>.</p><p>A ViewModel without separation of concerns is difficult to test, maintain and contains code you can&#8217;t reuse.</p><p>Although we&#8217;re only adding two numbers here, brushing the issue under the carpet will have consequences later down the line.</p><p>For example in addition to adding numbers what if another developer was given the task of storing the result in a database.</p><p>If the ViewModel was as it is now, with no <a
href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>, there is a chance they would put the code to store the value in the calculate method like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    // Calculate result
    Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();

    // Store value in database
    DatabaseConnection connection = new DatabaseConnection();
    DatabaseCommand command = new DatabaseCommand(&quot;TSQL TO STORE RESULT&quot;, connection);
    command.ExecuteNonQuery();
}
</pre><p>Now the ViewModel would be responsible for two things.  Next it would be three and this would continue until someone decides to separate the concerns or it gets to a stage where it&#8217;s impossible to work with let alone read.</p><h3 class="subheading">Refactoring the ViewModel to follow the single responsibility principle</h3><p>Let’s start by creating a class for calculating numbers.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Calculator
{
    public int Add(int firstValue, int secondValue)
    {
        return firstValue + secondValue;
    }
}
</pre><p>Notice how the parameters passed to the method are integers, the calculator doesn&#8217;t accept string values.</p><p>What we are saying here is while it&#8217;s acceptable for the ViewModel to use strings for storing numbers the domain layer (or business logic if you prefer) does not.</p><p>In other words the add method does nothing more than add two numbers together.  Validation should be handled elsewhere.</p><p>This makes the unit tests for the calculator very easy to write</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_calculating_numbers
{
    [Test]
    public void Should_be_able_to_add_two_numbers_together()
    {
        // Arrange
        Calculator calculator = new Calculator(); 

        // Act
        var result = calculator.Add(5, 5);

        //Assert
        Assert.That(result, Is.EqualTo(10));
    }
}
</pre><p>The code below shows how the ViewModel <strong>could</strong> create an instance of the Calculator class and call the Add Method.  Notice how I say could and not should.  We&#8217;ll see why later in the series.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>As <a
href="http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule">good boy scouts</a> we have ‘left the ViewModel cleaner than we found it’.</p><p>By following the single responsibility principle we have created a ViewModel which is a better canvas for other developers to work with.</p><p>If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.  So if you’re thinking why is the calculator class tightly coupled to the ViewModel?  Find out how this can be resolved by <a
href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/"> applying SOLID design principles using MEF in Silverlight and WPF</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>How NBuilder Could Help You Write Better .Net Unit Tests</title><link>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/</link> <comments>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/#comments</comments> <pubDate>Wed, 10 Mar 2010 22:00:51 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[NBuilder]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=618</guid> <description><![CDATA[One of the biggest challenges when creating unit tests is to come up test data. It makes sense having someone other than you test your code, so how about having someone other than you generate the test input for your .Net unit tests. Data generation tools aren’t new concept and they come in many different [...]]]></description> <content:encoded><![CDATA[<p>One of the biggest challenges when creating unit tests is to come up test data.  It makes sense having someone other than you test your code, so how about having someone other than you generate the test input for your .Net unit tests.</p><p>Data generation tools aren’t new concept and they come in many different forms.  When I first saw <a
href="http://www.red-gate.com/products/sql_data_generator/index.htm">Red Gate Sql Data Generator</a> a couple of years ago, I thought to myself it&#8217;s a shame you need a database because this would have been great for unit and integration tests.</p><p>In this blog post I want to show you how <a
href="http://nbuilder.org">NBuilder</a> can be used when unit testing with .Net objects.  The NBuilder assembly can be downloaded here <a
href="http://code.google.com/p/nbuilder/">http://code.google.com/p/nbuilder/</a>.</p><p>In this blog post we will be using the product and category classes below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Product
{
    public Product()
    {
        Categories = new List&lt;Category&gt;();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Rating { get; set; }
    public decimal Price { get; set; }
    public bool InStock { get; set; }
    public List&lt;Category&gt; Categories { get; set; }

    public override string ToString()
    {
        return String.Format(&quot;Id:{0}, Name:{1}, Rating:{2}, Price:{3}, InStock:{4}, Categories:{5}&quot;, Id, Name, Rating, Price, InStock, Categories.Count);
    }
}

public class Category
{
    public string Name { get; set; }
}
</pre><h3 class="subheading">NBuilder default values</h3><p>The product class contains a variety of types.  When you run the following code to create 10 products</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Should_Create_Ten_Products()
{
    var products = Builder&lt;Product&gt;.CreateListOfSize(10).Build();
    products.Count().ShouldEqual(10);
}
</pre><p>this is the output</p><table
border=1><tr
align="center"  bgcolor="grey"><td>Id</td><td>Name</td><td>Rating</td><td>Price</td><td>InStock</td><td>Categories Count</td></tr><tr
align="center"><td>00000000-0000-0000-0000-000000000001</td><td>Name1</td><td>1</td><td>1</td><td>False</td><td>0</td></tr><tr
align="center"  bgcolor="#F1EDED"><td>00000000-0000-0000-0000-000000000002</td><td>Name2</td><td>2</td><td>2</td><td>True</td><td>0</td></tr><tr
align="center"><td>00000000-0000-0000-0000-000000000003</td><td>Name3</td><td>3</td><td>3</td><td>False</td><td>0</td></tr><tr
align="center"  bgcolor="#F1EDED"><td>00000000-0000-0000-0000-000000000004</td><td>Name4</td><td>4</td><td>4</td><td>True</td><td>0</td></tr><tr
align="center"><td>00000000-0000-0000-0000-000000000005</td><td>Name5</td><td>5</td><td>5</td><td>False</td><td>0</td></tr><tr
align="center"  bgcolor="#F1EDED"><td>00000000-0000-0000-0000-000000000006</td><td>Name6</td><td>6</td><td>6</td><td>True</td><td>0</td></tr><tr
align="center"><td>00000000-0000-0000-0000-000000000007</td><td>Name7</td><td>7</td><td>7</td><td>False</td><td>0</td></tr><tr
align="center"  bgcolor="#F1EDED"><td>00000000-0000-0000-0000-000000000008</td><td>Name8</td><td>8</td><td>8</td><td>True</td><td>0</td></tr><tr
align="center"><td>00000000-0000-0000-0000-000000000009</td><td>Name9</td><td>9</td><td>9</td><td>False</td><td>0</td></tr><tr
align="center"  bgcolor="#F1EDED"><td>00000000-0000-0000-0000-00000000000a</td><td>Name10</td><td>10</td><td>10</td><td>True</td><td>0</td></tr></table><p><br/></p><ul><li>For strings NBuilder suffixes the index number to the name of the property e.g. Name1</li><li>For numeric values such as int and decimal the default value is the index number</li><li>For guids a hexadecimal range is used</li><li>Boolean values alternate between true and false for each product</li><li>The categories collection is left empty.  This would have been null if we didn&#8217;t create a new collection in the constructor of the product class</li></ul><h3 class="subheading">Changing how NBuilder default values are created</h3><p>I really like how you can customize NBuilder and use your own convention for creating default values.</p><p>For example what if we wanted to change how guids are created.</p><p>One way to do this is to inherit from the RandomValuePropertyNamer class and override the GetGuid method as shown below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class JagsRandomValuePropertyNamer : RandomValuePropertyNamer
{
    protected override Guid GetGuid(System.Reflection.MemberInfo memberInfo)
    {
        return Guid.NewGuid();
    }
}
</pre><p>After setting the default property namer, all guids are created by calling Guid.NewGuid()</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Product_Should_Have_Guid_Assigned()
{
    BuilderSetup.SetDefaultPropertyNamer(new JagsRandomValuePropertyNamer());

    var product = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p =&gt; p.Id = Guid.NewGuid())
        .Build();

    product[0].Id.ToString().ShouldNotEqual(&quot;00000000-0000-0000-0000-000000000001&quot;);
}
</pre><h3 class="subheading">Using the WhereAll method to set the InStock to always be true</h3><p>What if we wanted to change the InStock value to true for all the products in the collection.  This can be done using the WhereAll method as shown in the code below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void All_Products_Should_Be_In_Stock()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p =&gt; p.InStock = true)
        .Build();

    products.All(p =&gt; p.InStock).ShouldBeTrue();
}
</pre><h3 class="subheading">Using NBuilder to set parts of a collection</h3><p>There are two ways you can use Nbuilder to set values in parts of a collection.  The first is by using the first or last methods like so</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void First_Two_Products_Should_Be_In_Stock()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereTheFirst(2)
            .Have(p =&gt; p.InStock = true)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[1].InStock.ShouldBeTrue();
}
</pre><p>the other is to use sections</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Mixture_Of_Products_In_Stock_Using_Sections()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereSection(0, 1)
            .Have(p =&gt; p.InStock = true)
        .WhereSection(2, 9)
            .Have(p =&gt; p.InStock = false)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[2].InStock.ShouldBeFalse();
}
</pre><h3 class="subheading">Using the UniqueRandomList to create unique random lists&#8230;</h3><p>So far we haven&#8217;t done anything with the category property.</p><p>What if you wanted to build a product collection with each product having a random number of categories?</p><p>By calling the HaveDoneToThem and the UniqueRandomList methods we can create a set of products with having different categories to one another</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Products_With_Random_Categories()
{
    var categories = Builder&lt;Category&gt;
        .CreateListOfSize(100)
        .Build();

    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
        .HaveDoneToThem(p =&gt; p.Categories.AddRange(Pick&lt;Category&gt;.UniqueRandomList(2).From(categories)))
        .Build();

    var productCategoryOne = products[0].Categories[0].Name;
    var productCategoryTwo = products[1].Categories[0].Name;

    productCategoryOne.ShouldNotBeTheSameAs(productCategoryTwo);
}
</pre><h3 class="subheading">Extending NBuilder with a Lorem Ipsum string generator</h3><p>One thing I really like about NBuilder is the ability to extend it.</p><p>The code below shows how easy it is to have product names randomly using Lorem Ipsum just by creating a extension method like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public static class StringExtensions
{
    public const string LoremIpsum = &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;;

    public static IOperable&lt;Product&gt; HavingRandomLoremIpsumProductName(this IOperable&lt;Product&gt; operable)
    {
        ((IDeclaration&lt;Product&gt;)operable).ObjectBuilder.With(x =&gt; x.Name = LoremIpsum.Substring(0, new Random().Next(446)));
        return operable;
    }
}
</pre><p>this can be used to generate products with random names like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void Products_With_Random_LoremIpsum_Names()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .HavingRandomLoremIpsumProductName()
        .Build();

    var nameOfProductOne = products[0].Name;
    var nameOfProductTwo = products[1].Name;

    nameOfProductOne.ShouldNotBeTheSameAs(nameOfProductTwo);
}
</pre><h3 class="subheading">Jag Reehal’s Final Thought on &#8216;How NBuilder Could Help You Write Better .Net Unit Tests’</h3><p>I think frameworks like NBehave could really have a big impact on how you go about having to create test data.  The fluent interface is fantastic and it&#8217;s so easy to customize.</p><p>NBuilder contains a lot more features than I have covered in this post so if you like what you&#8217;ve seen make sure you check out the <a
href="http://nbuilder.org/Documentation">NBuilder documentation</a>.</p><p>For the future I’m hoping <a
href="http://fluentnhibernate.org/">Fluent NHibernate</a> and NBuilder could work together.  For example when you define class maps in Fluent NHibernate you can specify the length of string column.  If NBuilder could use information like this when generating data that would really be something special.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Pimp Up Your Unit Test Assertions</title><link>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/</link> <comments>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/#comments</comments> <pubDate>Wed, 13 Jan 2010 14:21:35 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=574</guid> <description><![CDATA[In this post I’m going to show you how you can write your unit test assertions to read more fluently and allow you to be more productive. The Plain Jane Unit Test Assertion This is what most developers will start off using. No problem with the equals assertion it easy enough to read and use. [...]]]></description> <content:encoded><![CDATA[<p>In this post I’m going to show you how you can write your unit test assertions to read more fluently and allow you to be more productive.</p><h3 class="subheading">The Plain Jane Unit Test Assertion</h3><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void The_Plain_Jane_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.AreEqual(firstString, secondString);

    // Greater Than
    Assert.Greater(bigNumber,smallNumber);

    // Less Than
    Assert.Less(smallNumber,bigNumber);
}
</pre><p>This is what most developers will start off using.  No problem with the equals assertion it easy enough to read and use.</p><p>However when using the greater or less than assertions, it’s not clear if the first argument should be the lower or the higher value as shown in the screen shot below.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/NUnitAssertConfusion.png" alt="NUnit Assert Confusion" style="border: solid #000000 1px;"/></p><p>This distraction can easily stop your flow.</p><h3 class="subheading">The More Fluent NUnit Test Assertion</h3><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void The_More_Fluent_Nunit_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.That(firstString, Is.EqualTo(secondString));

    // Greater Than
    Assert.That(bigNumber, Is.GreaterThan(smallNumber));

    // Less Than
    Assert.That(smallNumber, Is.LessThan(bigNumber));
}
</pre><p>The unit test assertions read a lot more fluently, we no longer have to be concerned about the order of arguments.</p><p>If you don’t want to use another third party library, this is for you.</p><h3 class="subheading">The Super Fluent NBehave Spec Assertion</h3><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void The_Super_Fluent_NBehave_Spec_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    firstString.ShouldEqual(secondString);

    // Greater Than
    bigNumber.ShouldBeGreaterThan(smallNumber);

    // Less Than
    smallNumber.ShouldBeLessThan(bigNumber);
}
</pre><p>This example uses the NBehave Spec Framework which you can download from the <a
href="http://nbehave.org/">NBehave</a> site.  In addition to being very easy to understand, the use of extension methods means there is a lot less noise.</p><p>Some developers will be concerned by losing the word ‘Assert’ in the line that does the assertion.  If you arrange your tests using the <strong>Arrange, Act, Assert</strong> pattern this should not be a problem.  See the example below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Test]
public void The_NBehave_Spec_Assertion_Using_Arrange_Act_Assert()
{
    // Arrange
    const int inputValue = 1;

    // Act
    var result = inputValue + 1;

    // Assert
    result.ShouldBeGreaterThan(inputValue);
}
</pre>]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Ever Thought About Changing How You Name Unit Tests?</title><link>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/</link> <comments>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/#comments</comments> <pubDate>Mon, 11 Jan 2010 12:40:04 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=556</guid> <description><![CDATA[In the last couple of months I’ve seen a new convention of how developers are naming their unit test classes. Traditionally the naming convention most developers use is to append the word ‘Tests’ to the class name as shown below. There is absolutely nothing wrong with it, but this can lead to problems because a [...]]]></description> <content:encoded><![CDATA[<p>In the last couple of months I’ve seen a new convention of how developers are naming their unit test classes.</p><p>Traditionally the naming convention most developers use is to append the word ‘Tests’ to the class name as shown below.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class UserValidation
{
}

[TestFixture]
public class UserValidationTests
{
}
</pre><p>There is absolutely nothing wrong with it, but this can lead to problems because a test class can become unwieldy and difficult to maintain either because it’s too long, testing a lot of different concerns or both.</p><p>In some cases it would make more sense to take different approach and adopt an alternative naming convention.  Sticking with the example above instead of having tests for validating a user in one class, a new class could be created for each concern.  So instead of</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class UserValidationTests
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid(&quot;123456&quot;);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}
</pre><h3 class="subheading">we create two test classes</h3><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class When_Validating_A_Users_Username
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }
    }

    [TestFixture]
    public class When_Validating_A_Users_Password
    {
        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid(&quot;123456&quot;);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}
</pre><p>I think this behavior driven development type naming convention will help focus on the problem you are solving and nothing more.  This is very useful when doing test driven development.</p><p>When I first saw tests written like this my first thought was how am I going to find the all the tests for User Validation because they are no longer in a single class?  If this is a problem for you think about using namespaces, folders or test attributes to organise your tests.  Don’t forget if you use tools like <a
href="http://www.jetbrains.com/resharper/index.html">ReSharper</a> help you find where a class is being used very easily.</p><p>Remember this is about renaming your tests classes and not your methods. So even if you follow the <a
href="http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx">MethodName_StateUnderTest_ExpectedBehavior</a> pattern for test methods this could still work.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Creating the animals game using Asp.Net MVC, jQuery and jQueryUI</title><link>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/</link> <comments>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/#comments</comments> <pubDate>Wed, 02 Dec 2009 09:36:50 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Asp.Net MVC]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery UI]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=483</guid> <description><![CDATA[A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the ‘Having fun with jQuery UI’ blog post. In this post we will go through how to create the game using ASP.NET MVC, jQuery and jQuery UI. The screenshot below shows the game [...]]]></description> <content:encoded><![CDATA[<p>A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the <a
href="http://www.arrangeactassert.com/having-fun-with-jquery-ui/">‘Having fun with jQuery UI</a>’ blog post.</p><p>In this post we will go through how to create the game using <a
href="http://www.asp.net/mvc/">ASP.NET MVC</a>, <a
href="http://jquery.com/">jQuery</a> and <a
href="http://jqueryui.com/">jQuery UI</a>.</p><p>The screenshot below shows the game running.</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ScreenshotOfGameUsingASP.NET-MVC-jQueryAndjQueryUI.png" alt="Screenshot of Game using Asp.Net MVC, jQuery and jQueryUI" /></p><p>The code used for creating the game in ASP.NET MVC, jQuery and jQuery UI can be downloaded <a
href="http://cid-8a29bf85dc9538dc.skydrive.live.com/self.aspx/.Public/GameUsingAspNetMVCandJQueryUI.zip">here</a>.</p><h3 class="subheading">Getting Started</h3><p>Instead of three animals used in the demo, the game now contains fourteen.   I’ve created a repository which returns the animals.  To keep things simple there’s no database here, instead the animals are hard coded.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;

namespace GameUsingAspNetMVCandJQueryUI.Core.Repository
{
    public class AnimalsRepository : IAnimalsRepository
    {
        public IQueryable&lt;Animal&gt; GetAll()
        {
            return new Animal[]
                       {
                           new Animal(){Name = &quot;Cow&quot;},
                           new Animal(){Name = &quot;Cat&quot;},
                           new Animal(){Name = &quot;Chicken&quot;},
                           new Animal(){Name = &quot;Dog&quot;},
                           new Animal(){Name = &quot;Elephant&quot;},
                           new Animal(){Name = &quot;Giraffe&quot;},
                           new Animal(){Name = &quot;Hippo&quot;},
                           new Animal(){Name = &quot;Lion&quot;},
                           new Animal(){Name = &quot;Monkey&quot;},
                           new Animal(){Name = &quot;Mouse&quot;},
                           new Animal(){Name = &quot;Owl&quot;},
                           new Animal(){Name = &quot;Penguin&quot;},
                           new Animal(){Name = &quot;Pig&quot;},
                           new Animal(){Name = &quot;Sheep&quot;},
                       }
                .AsQueryable();
        }
    }
}
</pre><h3 class="subheading">Command Query Separation</h3><p>One of the features I have added is to ensure a correct answer for the current game could not be the correct answer in the next.  As the repository class was responsible for getting animals, having it contain any logic would violate good design principles.</p><p>So the logic goes into the service layer which returns a data transfer object for animals and the correct answer.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.ExtensionMethods;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;

namespace GameUsingAspNetMVCandJQueryUI.Core.Service
{
    public class AnimalsService : IAnimalsService
    {
        private readonly IAnimalsRepository _animalsRepository;

        public AnimalsService(IAnimalsRepository animalsRepository)
        {
            _animalsRepository = animalsRepository;
        }

        public AnimalsDto GetAnimalsForGameWithCorrectAnswer(int numberOfAnimals, string previousAnimal)
        {
            AnimalsDto animalsDto = new AnimalsDto();
            animalsDto.Animals = _animalsRepository
                .GetAll()
                .Where(a =&gt; a.Name != previousAnimal)
                .Shuffle()
                .Take(numberOfAnimals);

            animalsDto.CorrectAnswer = animalsDto.Animals.Shuffle().First().Name;

            return animalsDto;
        }
    }
}
</pre><p>This also makes testing easier because the tests can focus on making sure the service is doing what it should like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
using NBehave.Spec.NUnit;
using NUnit.Framework;
using Rhino.Mocks;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class AnimalsServiceTests
    {
        private IAnimalsService _animalsService;
        private IAnimalsRepository _animalsRepository;

        private readonly IQueryable&lt;Animal&gt; _animalsStub = new Animal[]
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           }.AsQueryable();

        [SetUp]
        public void SetUp()
        {
            _animalsRepository = MockRepository.GenerateStub&lt;IAnimalsRepository&gt;();
            _animalsService = new AnimalsService(_animalsRepository);
        }

        [Test]
        public void Should_Exclude_Previous_Animal_When_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            var previousAnimal = _animalsStub.First();

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal.Name);

            // Assert
            result.Animals.Count(a =&gt; a.Name == previousAnimal.Name).ShouldEqual(0);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = String.Empty;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result..Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Null()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = null;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result.Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Correct_Answer_Should_Not_Be_Empty()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);            

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, null);

            // Assert
            result.CorrectAnswer.ShouldNotBeEmpty();
        }
    }
}
</pre><h3 class="subheading">The LINQ Shuffle</h3><p>Even though we have removed the previous answer, if the animals were returned as they are the answer would just be the next one in the list.  So to keep the game exciting, a shuffle extension method is used to shuffle the answers.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;

namespace GameUsingAspNetMVCandJQueryUI
{
    public static class GameExtensions
    {
        public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; items)
        {
            var rnd = new Random();
            IEnumerable&lt;int&gt; numbers = Enumerable.Range(0, items.Count()).OrderBy(r =&gt; rnd.Next());
            var randomItems = new List&lt;T&gt;();
            foreach (int number in numbers)
            {
                randomItems.Add(items.Skip(number).First());
            }
            return randomItems;
        }
    }
}
</pre><p>This can be unit tested as shown below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Collections.Generic;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using NUnit.Framework;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class GameExtensionsTests
    {
        [Test]
        public void Can_Shuffle_Animals()
        {
            List&lt;Animal&gt; animals = new List&lt;Animal&gt;()
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           };
            IList&lt;Animal&gt; result = animals.Shuffle().ToList();
            Assert.IsFalse(
                animals[0].Equals(result[0]) &amp;&amp;
                animals[1].Equals(result[1]) &amp;&amp;
                animals[2].Equals(result[2]),
                &quot;Animals should have been shuffled&quot;);
        }
    }
}
</pre><h3 class="subheading">What happens when a player opens the game in their browser?</h3><p>When the page loads an Ajax call is made using jQuery to an Asp.Net MVC action method which returns a JsonResult.</p><pre class="brush: jscript; gutter: false; title: ; toolbar: true; notranslate">
   $.getJSON(&quot;/Game/GetAnimals&quot;,
            { numberOfAnimals: numberOfItemsToGet, previousAnimal: correctAnswer.text() },
            function(data) {
                addItems(data);
                $(&quot;#droppable&quot;).droppable(droppableOptions);
                assignDraggables();
                hideItemsForLevel();
                setUpSlider();
                setTimeout(function() {
                    instructions.text(instructionsText);
                    items.show();
                }, 1000);
            });
</pre><p>Two parameters are passed to the action method, one for the previous answer and the other for the number of animals required.  The reason for this is because we don’t want to transfer more data over the wire than required, why return fourteen animals when only six are required?</p><p>The ‘GetAnimals’ Asp.Net MVC action method shown below serializes the view model returned by the service layer into JSON.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System.Web.Mvc;
using GameUsingAspNetMVCandJQueryUI.Core.Service;

namespace GameUsingAspNetMVCandJQueryUI.Controllers
{
    [HandleError]
    public class GameController : Controller
    {
        private readonly IAnimalsService _animalsService;

        public GameController(IAnimalsService animalsService)
        {
            _animalsService = animalsService;
        }

        public ActionResult Index()
        {
            return View(&quot;Index&quot;);
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = &quot;*&quot;)]
        public JsonResult GetAnimals(int numberOfAnimals, string previousAnimal)
        {
            return Json(_animalsService.GetAnimalsForGameWithCorrectAnswer(numberOfAnimals,previousAnimal));
        }
    }
}
</pre><blockquote><p>Notice how I have to be explicit about how I do NOT want the JsonResult to be cached.  If you don&#8217;t add this Internet Explorer will cache the result and you will get the same animals.</p></blockquote><h3 class="subheading">Using the jQuery and jQuery UI in the ASP.NET MVC View</h3><p>The JavaScript used the demo was good enough to perform the dragging and dropping of pictures so the good news is we can use it again here.</p><p>An additional feature I have added is to allow the player to change the difficulty of the game by choosing how many animals are shown on the screen.</p><p>To do this I used the jQuery UI slider and jQuery fade functionality.  The reason I used fade rather show/hide in jQuery was because I didn’t want the animals to move position when a user changed the difficulty as this would have resulted in a poor user experience by confusing the player.</p><p>Currently the message which tells the player if they have selected an incorrect answer is shown when the user stops dragging the animal.  This is a problem because if the user drags a correct animal but doesn’t drop it on the droppable a message isn’t shown.  If I find a fix for this I’ll update the code and this post.</p><h3 class="subheading">Jag Reehal’s Final Thought on ‘Creating the animals game using Asp.Net MVC, jQuery and jQueryUI’</h3><p>I’ve been using jQuery for a while now and I still love it.</p><p>The jQuery UI library is very good and the <a
href="http://jqueryui.com/about">jQuery UI team</a> have done a fantastic job creating demos and documentation.</p><p>I really like how you can create your own custom javascript file which only contains the features you require from the library.</p><p>No doubt some people will question why the service is returning a data transfer object.  I could have returned a collection of animals to the ASP.NET MVC controller and have it create an object to pass to the view.  The reason I didn’t do this is because I know the data transfer object will be used by another user interface layer (Silverlight) and because this would have bloated the controller and that’s not good.  A <a
href="http://www.arrangeactassert.com/asp-net-mvc-controller-best-practices-%E2%80%93-skinny-controllers/">best practice for ASP.NET MVC is to have skinny controllers</a>.</p><p>The images for the animals used in the game are from <a
href="http://www.openclipart.org">http://www.openclipart.org</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>A solution for the Resharper Test Runner not picking up your latest changes</title><link>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/</link> <comments>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/#comments</comments> <pubDate>Tue, 17 Nov 2009 00:19:12 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Resharper]]></category> <category><![CDATA[Unit tests]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=463</guid> <description><![CDATA[For a while now I thought there was a bug when using Resharper to run my unit tests. Because my latest changes were not being picked up, I always had to build my solution first and then run the unit tests. Not anymore. Today a colleague showed me this &#8216;Build Settings&#8217; option Selecting ‘Always Build’ [...]]]></description> <content:encoded><![CDATA[<p>For a while now I thought there was a bug when using <a
href="http://www.jetbrains.com/resharper/">Resharper</a> to run my unit tests.</p><p>Because my latest changes were not being picked up, I always had to build my solution first and then run the unit tests.</p><p><strong>Not anymore.</strong></p><p>Today a colleague showed me this &#8216;Build Settings&#8217; option</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ResharperUnitTestRunnerWindow.png" alt="Resharper Unit Test Runner Window" /></p><p><br/><br
/> Selecting ‘Always Build’ makes sure the latest changes (even to config files) are used when running unit tests. The default is &#8216;Automatic&#8217; as shown above.</p><p>Just be aware of the size of your solution will have an impact on how long the tests will take to run.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Served from: www.arrangeactassert.com @ 2012-02-05 23:30:01 by W3 Total Cache -->
