Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool

  • Partial Mocks with the StructureMap AutoMocker

    If you have not checked out the new AutoMocking Container that is part of StructureMap 2.5 I would highly suggest you do, it rocks.

    I thought I would show how simple it is to create a PartialMock on the Class under Test (CUT) when using the RhinoAutoMocker.

    Our Class we want to mock

    public class VisitReassignmentRule : PersistingRule
    {
    
        public VisitReassignmentRule( ISynchronizationRepository synchronizationRepository, 
    	IValidationRepository validationRepository, 
            IValidationLogger validationLogger ) : base( validationRepository, validationLogger )
        {
            SynchronizationRepository = synchronizationRepository;
        }
    
        public override InvocationActions ProcessRule( DataSet ds )
        {
    
    	// logic goes here
    
            return null;
        }
    
        public override bool DataIsInviolationOfRule( DataSet dataSet )
        {
            return false;
        }
    
        private ISynchronizationRepository SynchronizationRepository { get; set; }
    }
    
    

    Mocking Code

    [Test]
    public void ProcessRule_ViolatesRule()
    {
        	var rule = new RhinoAutoMocker();
    
    	// This line here tell the mocking container to make it a partial ( I know, the method name tells u that to)
        	rule.PartialMockTheClassUnderTest();
        	rule.ClassUnderTest.Expect( x => x.DataIsInviolationOfRule( null ) ).IgnoreArguments().Return( false ).Repeat.Any();
    
    	// actually call the method
        	rule.ClassUnderTest.ProcessRule( dataset );
    }
    

    As you can see, telling the AutoMocking container that you want the Class under Test to be a partial is very easy.  The one thing you want to make sure you do is not use the .Get<> syntax and just use the .ClassUnderTest syntax to set your expectation.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Chicago Alt.Net Meeting location for tomorrow has changed.

    Sorry for the last minute notice, but we have to change locations for tomorrow’s meeting.  If you are planning on coming (and you should) please take not of the new location

    NEW LOCATION
    Redpoint Technologies
    Sears Tower
    233 South Wacker Dr.
    Suite 750
    Chicago, Illinois 60606

    Same time, same everything else.

    Sorry again for the late notice.

    Till next time,

  • Save Dataset contents to XML and Null Values

    Today I needed to save a fully populated dataset as xml to my drive in order to simplfly unit testing.  I thought this would be pretty straight forward, but as it turns out it was not.  There is one little wrinkle that may bite you if you are not careful.  Below I will describe what I tried and why it failed and finally what worked.

    Problem: I need to save a fully populated Dataset as XML to disk

    Solution Attempt 1: Use DataSet.WriteXml( LocationOnDisk )

    This worked, mostly.  I was able to get the XML document and reload it into a a dataset using DataSet.ReadXml( LocationOnDisk ).  A problem arose because one of my columns was always null.  And by default simply doing a WriteXml does not save schema information. More information on this here.

    Solution Attempt 2: Use DataSet.WriteSchema (LocationOnDisk) then user DataSet.WriteXml( LocationOnDisk)

     This worked.  By saving my schema information for the dataset I am later able to repopulate the data and have my null values replaced.  In order to do this all you have to do is the following.

    DataSet ds = new DataSet();
    ds.ReadXmlSchema( XsdFileLocation );
    ds.ReadXml( XmlFileLocation );

    I know this seems pretty trival, but If you do not understand how Xml and schemas work you could spin your wheels for a while trying to figure out why your column/data was not repopulated.

    Hope this helps someone,

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Using the RhinoAutoMocker that is part of StructureMap 2.5

    One of the new features that is part of the next release of StructureMap 2.5 is a AutoMocking Container. 

    What is an AutoMocking Container, well per Jacob over at Eleutian an AutoMocker is

    AutoMockingContainer is simply a IoCContainer with a custom facility and dependency resolver that supplies a Mock (RhinoMock) for any interface that is resolved.

    My definition is a little more straight forward and uses simpler word (remember I am a simpleton :))

    An AutoMocking container is simply a tool that will inject mock dependencies into your object for you.

    What I want to do today is show how an AutoMocking Container can reduce the amount of code/noise from your tests.   I am going to first show a tests that simply uses RhinoMocks then that same test that uses the RhinoAutoMocker

    Test with only RhinoMocks

    [Test]
    public void NoAutoMocker()
    {
    	var mockProvider = MockRepository.GenerateMock<IPersistingRulesProvider>();
            var mockRepository = MockRepository.GenerateMock<ISynchronizationRepository>();
            var mockPersistanceProvider = MockRepository.GenerateMock<IPersistanceProvider>();
            var mockLogger = MockRepository.GenerateMock<ILogger>();
    
    	// Expectations
            mockProvider.Expect(x => x.ExecuteRules(null)).IgnoreArguments().Throw(new Exception("Do not care what this is"));
            mockRepository.Expect(x => x.StartTransaction()).Repeat.Once();
            mockRepository.Expect(x => x.RollbackTransaction()).Repeat.Once();
            mockRepository.Expect( x => x.CommitTransaction() ).Repeat.Never();
    
    	var persitingPipeline = new PersistingPipeline(mockProvider, mockPersistanceProvider, mockRepository, mockLogger);
            var result = persitingPipeline.PersistChanges(new DataSet(), 0, 0, 0);
    
    	Assert.That( result, Is.Not.Empty );
    
    	mockRepository.VerifyAllExpectations();
    }
    
    

    This code above has a bit of noise.  Because my object has a dependency on 4 other objects i need to create mocks for each of these.  This creates more work and just adds to the test noise.

    Test with the RhinoAutoMocker

    [Test]
    public void WithAutoMocker()
    {
    	var mockPipeline = new RhinoAutoMocker<PersistingPipeline>();
    
    	mockPipeline.Get<IPersistingRulesProvider>().Expect( x => x.ExecuteRules( null ) ).IgnoreArguments().Throw( new Exception( "Do not care what this is" ) );
    	mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.StartTransaction()).Repeat.Once();
            mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.RollbackTransaction()).Repeat.Once();
            mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.CommitTransaction()).Repeat.Never();
    
    	var result = mockPipeline.ClassUnderTest.PersistChanges( new DataSet(), 0, 0, 0 );
    
    	Assert.That( result, Is.Not.Empty );
    
    }
    

    The code above does not require me to create mocks for each of my dependencies, the AutoMocker will do that for me.

    Also notice that when I need to set an expectation for a dependencies I can access it via the .Get<>() method. 

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Speaking engagements on the horizon

    I thought I would just drop a little note on some speaking engagements I will be doing over the next month or so.

    Oct 30th - Lake County (IL) .Net Users Group - Gorking the Asp.Net MVC Framework

    Nov 12th - TriNug - Raleigh .Net Users Group - Taking tests to the next level with Mocks (will dive into AutoMockers as well)

    Nov 15th - Raleigh Code Camp - Bending the Asp.Net MVC to do you bidding, the virtues of extensibility

    I would love to see all 3 of my readers come out to mock and ridicule me at any of these 3 sessions.

    Till next time,

  • Unit Tests to the rescue

    Today started off in a bad, bad way.  Because of some issues I had earlier in the week with my source control repository (SCR) I was doing a ton of work offline.  Today I was able to regain access to my SCR I decided to do a full get.  I was fully expecting SourceOffSite (crappy overlay tool on top of VSS -- BTW, VSS is the devil) to prompt me for conflicts or do merges...... NOPE

    When I finished doing my SCR pull I re-opened Visual Studio and did a compile.  To my dismay I had TONS of build errors.  After about 3 seconds of looking into the errors I knew I was screwed.  It turns out I lost about 2 days worth of code because the source files were not merged they were overwritten....THIS SUCKS

    The good news for me is that much of the code that was overwritten was plumbing work and was fixed in about 1 hour.  However, there was a bit of logic code that was overwritten as well.  This is where my unit tests came to the rescue.

    Because I has pretty good code coverage with my tests I was able to re-create the logic with very little fear that the new implementation changed the intent of the original logic.  Also because I had my tests I was able to infer logic based on what the tests were meant to verify.

    I am not trying to say that tests made this all ok, but having my tests did make me feel a little better in thinking that I have not broken anything.  Sadly, I wasted a large portion of my morning doing this.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • 2 of the Devlicio.us crew is awarded the Microsoft MVP

    It is that time of year again, the time where Microsoft hands out the MVP awards.

    This time round both myself (C#) and Michael Neel (aka ViNull) (asp.net) were awarded the MVP.  This is pretty cool and I hope we can live up to the MVP'ness

    Till next time,

  • Some comments are a total waste of time

    I am all for comments in code (gasp I know) but some are just a total waste of time.

    Case in point.  I came across this today.

    /// <summary>
    /// Commit Transaction.
    /// </summary>
    public void CommitTransaction()
    {
    ........
    }

    WTF, I guess putting the Commit Transaction comment makes it more clear that the method "CommitTransaction' commits a transaction.

    As I said above, I am for comments, but I have a few simple rules I like to follow.

    1. Don't repeat yourself
      Like the example above don't waste my time telling me via a comment what the method/property name does when the name of the method/comment clearly states that information.
    2. Comment intent, not logic
      I know how to read if statements, and for loops.  Please do not tell me 'doing a look' or 'doing a check' because that is clear from the code.  However, please tell me why you are doing the loop if it is not obvious.  If there is some funky logic in the loop, that I need to know.
    3. Keep it short, and 'timeless'
      I do not want to read a novel.  I want to read 1 maybe 2 sentences and know enough to move on.
    4. If it is a 'Hack' it needs to be stated as such
      We all have added 'Hacks' to our code.  These are things that would not make sense to the casual observer but there is a reason why they are being done.  THESE MUST BE COMMENTED because if they are not someone else in the future is going to come along and repeat all your mistakes.

    Ok, rant over.

    Till next time,

    BTW, I removed that comment from my code base.

  • Clean build server with MSTest == FAIL

    It is no secret that I am not a fan of MSTest (read here for more rants on MSTests).  Today's rant is about how MSTest does not allow you to have a clean build server.

    Yea I know what you are thinking, here comes another long winded rant on MSTest.  Well this should not be too long winded, and hey, it is my blog and I can rant if I want to :).

    This week I was trying to setup our build server and I need it to run MSTest tests.  I know that MSTest does not run like NUnit, but thought for sure there was a way I could get my tests to run without having to install the full blown version of Visual Studio.  After a bit of searching and asking others I came to final conclusion that in fact you cannot get MSTest to run without Visual Studio. 

    This is an issue to me because when I setup my build server I like to keep it clean.  I do NOT want to install any 3rd party software.  The way I see it is like this.  If we are not going to install the software package on the end users computer, why should I need to install them on our build server, and the last time I checked we do not install Visual Studio on our end users computer.

    This is another issue to me because MSTest is the ONLY test framework (for .Net) that I know of that does not run with a single DLL placed into the bin (or any other output directory).  I just have to ask the genius' over in Redmond what the hell were they smoking when they decided to build MSTest.  It is pretty clear they had no prior knowledge of how to use the other tools such as NUnit, MBUnit or xUnit (I know, xUnit was not out yet).  I know this because of all the various testing frameworks MSTest is the one that does everything different.  You could argue they were on the cutting edge and were innovating, but I call BS on that.

    Anyway, I feel better now telling the world another reason why I am not a fan of MSTest.  Sadly I am stuck using it for now and at least in the short term as we have hundred of tests already written in MSTest.  But rest assured that I am on a crusade to get our team to switch from MSTest to NUnit (or any other logical framework).

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • StructureMap Automocker & FillDependencies Error(230)

    I have been giving the AutoMocker that is part of StructureMap 2.5 a go lately.  Today I was trying to setup my test and I get running into the following error:

    failed: StructureMap.StructureMapException: StructureMap Exception Code: 230
    Cannot call "FillDependencies" on type IGatheringPipeline. Check that the type is concrete and has no primitive arguments

    Everything looked right and I knew i could create my objects directly via the ObjectFactory method, but I just could not figure out what was wrong.  My 'bad' code is below.

    [TestMethod]
    public void IsSynchronizationNeeded_EnsureHitsRepository()
    {
        var pipelineMocker = new RhinoAutoMocker<IGatheringPipeline>();
    
        pipelineMocker.Get<iRepository>().Expect( x => x.DataNeedsSynchrnoization() ).Return( true ).Repeat.Once();
        
        var isSynchronizationNeeded = pipelineMocker.ClassUnderTest.IsSynchronizationNeeded();
    
        Assert.AreEqual( true, isSynchronizationNeeded );
    
    }
    

    After staring at the code and taking another look at its intent it dawned on me what the issue was.  I was creating the automocker with an interface and I wanted to call methods on that interface and actually have the logic execute.  In order to get this to work I simply needed to change my class in the auto mocker to the concrete.

    [TestMethod]
    public void IsSynchronizationNeeded_EnsureHitsRepository()
    {
        // Using the Concrete here
        var pipelineMocker = new RhinoAutoMocker<GatheringPipeline>();
    
        pipelineMocker.Get<iRepository>().Expect( x => x.DataNeedsSynchrnoization() ).Return( true ).Repeat.Once();
        
        var isSynchronizationNeeded = pipelineMocker.ClassUnderTest.IsSynchronizationNeeded();
    
        Assert.AreEqual( true, isSynchronizationNeeded );
    
    }
    

    After I changed my test to use the code above everything worked out well. 

    Hope this helps,

    Till next time,

     

    [----- Remember to check out DimeCasts.Net -----]

  • NAnt/MSbuild build error MSB4019 -- Missing Targets

    I was trying to setup our new build server today and received this error:

    error MSB4019: the imported project <Path to .net framework here>\Microsoft.CompactFramework.CSharp.targets was not found.

    At first I was a bit confused as to what was going one, how could you not find my targets file?  And of course this was working just fine on my laptop (always works on you machine), but not the build server.

    Before I dive into the solution for this, I would like to pause to review what was on the build box.

    Environment Overview:

    Build Server: Team City
    Build Script: NAnt
    Build Action: MSBuild
    Software Installed: .Net 2.0 SDK, .Net 3.5 SDK, .Net 3.5 Compact Framework SDK, need tools for build.  NO Visual Studio IDE's

    Onto the Solution:

    Ok, now that we know what the server setup was like, lets get onto the solution.

    For what ever reason my build server did not contain any .targets files for the compact framework.    These files are normally found in your c:\Windows\Microsoft.Net\Framework\v3.5 folder, but mine were missing.  The easiest way to fix this issue is to grab these files off of the server/laptop that has them and copy/paste them onto the server that does not.  This worked just fine for me.

    Note: My issue was with missing targets for the compact framework, but have heard reports of the same thing happening with other .targets files. 

    Hope this helps someone.

    Till next time,

  • Custom Formatters for YUI DataTable

    In a prior posting (here) I walked through how to add the YUI DataTable to your site.  Today I thought I would take that a step further and explain how to create custom formatters so your grid can look all fancy and stuff. 

    A custom formatter is a way to define a layout for the DataTable.  There are built in formatters, but you can also define your own.

    Here are the list of built in formatters (found in YUI docs):

    • "button" points to YAHOO.widget.DataTable.formatButton
    • "checkbox" points to YAHOO.widget.DataTable.formatCheckbox
    • "currency" points to YAHOO.widget.DataTable.formatCurrency
    • "date" points to YAHOO.widget.DataTable.formatDate
    • "dropdown" points to YAHOO.widget.DataTable.formatDropdown
    • "email" points to YAHOO.widget.DataTable.formatEmail
    • "link" points to YAHOO.widget.DataTable.formatLink
    • "number" points to YAHOO.widget.DataTable.formatNumber
    • "radio" points to YAHOO.widget.DataTable.formatRadio
    • "text" points to YAHOO.widget.DataTable.formatText
    • "textarea" points to YAHOO.widget.DataTable.formatTextarea
    • "textbox" points to YAHOO.widget.DataTable.formatTextbox

    Creating your own formatter is cake, with a few lines of code you are off to the races.

    IN order to create your own custom formatter you need to do 2 things.

    1. Create the actual formatter:
      // wanna create a custom formatter for the cell
      this.myCustomFormatter = function(elCell, oRecord, oColumn, oData) 
                  
      {
      
      	var name = oRecord.getData("Name");
              var episodeNumber = oRecord.getData("EpisodeNumber");
              elCell.innerHTML = "" + name + "";
                  
      };
      


      You will notice that the code above is actually creating a delegate callback that the DataTable will invoke.  It is inside this callback that all the 'magic' happens.
    2. Assign the formatter to the DataTable:
      // Add the custom formatter to the shortcuts 
      YAHOO.widget.DataTable.Formatter.myCustom = this.myCustomFormatter; 
      


      This code simply will assign your formatter to the Formatter collection that is part of the DataTable
    3. Tell the particular column on the DataTable which formatter to use:
      var myColumnDefs = [                    
      	{key:"EpisodeNumber", label:"#", width:30},
              {key:"Name", formatter:"myCustom"}, 
              {key:"EpisodeDate", label:"Release Date", width:100},
              {key:"Count", width:50}
      ];
      


      Pay close attention to this code, take notice where I use 'formatter:"myCustom".  The use of myCustom MUST match the name you assigned the formatter on the DataTable formatters collection.

    There you go, a quick overview on how to create and use a custom formatter for you your YUI DataTable.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Quote of the day

    I was listening to Episode #8 on DeepfriedBytes today and heard the greatest quote.

    In this episode Woody and Keith are speaking with Brad and Jim who both work over at Microsoft.  The quote goes a little like this:

    'We are a Microsoft shop here so we try to use Microsoft products'

    Sorry, I just found it great they they actually referred to them selves as a 'Microsoft shop'

    Till next time,

  • Upgrading a Smart Device Project to Compact Framework 3.5

    ***** Disclaimer: I am a total NOOBIE to working on Smart Device Projects *****

    Today I needed to upgrade on of our smart device projects from Compact Framework 2.0 to 3.5.  I figured that I could do this via the properties dialog, but could not (see image below).  But as you can see, the Target Framework option is no enabled.

     

    Being the guy I am (having now regard to totally screwing something up) I decided to take a look at the project file (.csproj) to see what I could learn from that.  Withen about 10 seconds of looking at the file I came across the following node.
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>

    I decided to change this to:
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>

    When I went back into my solution it asked to refresh based on the fact the files where changes.  After the refresh all was good.

    I know there HAS to be a better/cleaner/eaiser/safer way to do this, but I could not find it.  So, if there is please let me know.

    Hope this helps someone in the future,

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Testing your IoC Bindings

    One thing I like to do when I am using a IoC (Inversion of Control) container is to create simple test that ensure that my objects have been wired up correctly and can be created via the IoC container. 

    I know this may seem like overkill, but I feel that by having my IoC bindings covered by tests I am covering all my bases.

    So, what does testing my bindings do for me

    • Allows me to know if my object is configured correctly
      By having these tests I will know immediately if I have somehow broken my IoC bindings glue (yes, glue is the technical term in this case). 

      It is not hard to phantom that when making changes to your IoC bindings logic (either via config files or via inline code) you can mistakenly break something.  Having these tests provides me immediate feedback if this were to happen.
    • Allows me to know if my objects dependencies are configured correctly
      Setting up the wiring for your main object is only half the battle.  When using an IoC container many time you are going to have that container do some sort of Constructor Injection of your dependencies. 

      By having tests that simply create my object with IoC I will find out immediately if one of my dependency objects is not wired up.  This scenario is pretty common and having this test can save you some headaches.

    Here is the test code I use for my IoC bindings tests:

    [Test]
    public void CanCreateViaDI()
    {
        var iocObject = ObjectFactory.GetInstance< YourObjectHere >();
        Assert.That( iocObject, Is.Not.Null );

    }

    Hope this helps someone.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

More Posts Next page »

Our Sponsors

Red-Gate!

This Blog

Syndication

News