Showing posts with label Unit Testing. Show all posts
Showing posts with label Unit Testing. Show all posts

Wednesday, February 11, 2015

ReSharper 9.1 EAP - EAP02 is out!

ReSharper 9.1 EAP02 is available for download here: https://confluence.jetbrains.com/display/ReSharper/ReSharper+9.1+EAP



I know because after the VS2015 update - I couldn't run any of my tests anymore through the ReSharper test runner:



However - this is fixed in the EAP2, so go and get it if you're like me and want to work in VS2015 with ReSharper and like the ReSharper test runner.

Thanks ReSharper:


Monday, October 21, 2013

Geting code coverage with QUnit: Blanket.js

Yet another *.js -charm  this time blanket. It's a code coverage tool for your QUnit tests. It works like a charm and requires next-to-no effort.

BlanketJS

I've added the library to my QUnit tests that I'm running and it does at it says on the tin. Works like a charm. Go check it out at http://blanketjs.org/.


Below are some of the tests I'm running. By the way - I'm using the Ninja theme for QUnit: http://qunitjs.com/plugins/ - at the bottom.


Thursday, April 25, 2013

Quickly test your assemblies using MS Fakes

On hackernews I saw this article coming by about a feature that I didn't know about in VS 2012: adding fake assemblies. I can't go into it too deep - but it's super simple and very powerful. However - I also heard it's quite 'expensive' in terms of processing power which makes your tests a bit slow and that's annoying. So don't start faking everything right away.

On this topic - be sure to listen to the .NET Rocks! Podcast on testing with special guest Hendrik Lösch. AND there is an eBook about this feature available for download. Here are the links:

http://mikefourie.wordpress.com/2013/03/05/creating-the-better-unit-testing-with-microsoft-fakes-ebook/ 



A nice 101 on this feature: http://www.codeproject.com/Articles/582812/Unit-testing-with-Fakes-with-Visual-studio-Premium



And a very interesting podcast on testing on the .NET Rocks! podcast : http://www.dotnetrocks.com/default.aspx?showNum=865


Wednesday, April 24, 2013

Unit testing the EF DataContext using Moq and FakeDbSet

I came across a very sweet way of testing EF DataContexts: http://www.nogginbox.co.uk/blog/mocking-entity-framework-data-context . This guy figured it out.

What he does is:
- Change all DbSet<...> in your EF DataContext to IDbSet<...>
- Extract an interface
- Get NuGet package Moq : https://www.nuget.org/packages/moq
- Get NuGet package FakeDbSet : http://nuget.org/packages/FakeDbSet/

Setup a test datacontext with some data like so:

// Create mock unit of work
var mockDataContext = new Mock<IDataContext>();
var mockItemList= new InMemoryDbSet<item>(clearDownExistingData: true)
{
new item(FakeDepartureDate1, "drp1", "drp3", 1), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate1, "drp1", "drp3", 2), 
new item(FakeDepartureDate2, "drp2", "drp3", 4), 
new item(FakeDepartureDate2, "drp2", "drp4", 5), 
new item(FakeDepartureDate2, "drp2", "drp4", 5)
};
mockDataContext.Setup(m => m.itemList).Returns(mockItemList);

And presto - you can start testing against your fake data. I used it to prove my query worked correctly.

EntityFramework testing will be done like so from now on by me!

But - don't take my word for it - check out the guy who figured it out before me:


Saturday, December 8, 2012

Method pre-condition checking: IF, Assert and Contract.Requires

Recently I picked up on a different way of checking method pre- and post-conditions in c#: Code Contracts. In this post, I'll describe the three methods that I know of by providing an example and checking unit-test behavior:
  1. Good old 'if ()' checking with throwing exceptions
  2. Assertions, from the System.Diagnostics.Debug library
  3. Code contracts, form the System.Diagnostics.Contracts library, shipped with .NET framework 4
I've been playing around with it and I'm trying to make up my mind if I prefer any of the System.Diagnostics ways over the 'good-old' IF and exceptions.

Everyone uses division in order to demonstrate illegal argument handling, since division by 0 cannot be done, so why should I do it any differently? Let's look at a method:

        public static int Divide(int numerator, int denominator)
        {
            return numerator/denominator;
        }

Now, what we want to do is make sure that the denominator is larger than 0. Using the three mentioned methods, it would look something like this:


        // CASE 1: Throws exception in case pre-condition ( denominator > 0 ) is not met
        public static int DivideWithExceptionThrowing(int numerator, int denominator)
        {
            if (denominator == 0)
            {
                throw new DivideByZeroException("Denominator should be larger than zero");
            }
            return numerator / denominator;
        }

        // CASE 2: Fails assertion if pre-condition is not met
        public static int DivideWithAssert(int numerator, int denominator)
        {
            Assert.IsTrue(denominator > 0, "Denominator should be larger than zero");
            return numerator / denominator;
        }

        // CASE 3: Fails to meet contract requirements in case pre-condition is not met
        public static int DivideWithContract(int numerator, int denominator)
        {
            Contract.Requires(denominator > 0, "Denominator should not be larger than zero");
            return numerator / denominator;
        }
In case the last way of checking the pre-condition is new to you, check out this excellent guide. Although the namespaces are included in .NET framework 4.5, you do need to download the Visual Studio add-on for code contracts ( even if you are using VS2012 ) from here. After that you have to open solution properties and go to the code-contracts tab in order to set things up.
Also - I needed to set CONTRACTS_FULL compilation symbol in order for my ReSharper to stop fading out my Contract.Requires line, saying that it will be skipped ( as described here ).

Note that I can set the exception that needs to be thrown in case the pre-condition is not met, using Contract.Requires<ExceptionType>() syntax.

So now, how should we unit-test our three methods? I've set up three tests that supply a zero as denominator. Therefore - I'm checking for the exceptions using the ExpectedException attribute for all of these cases:

        [TestMethod]
        [ExpectedException(typeof(DivideByZeroException))]
        public void Divide_DividesByZero_ThrowsException()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithExceptionThrowing(numerator, denominator);
        }

        [TestMethod]
        [ExpectedException(typeof (AssertFailedException))]
        public void Divide_DividesByZero_FailsAssertion()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithAssert(numerator, denominator);
        }

        [TestMethod]
        [ExpectedException(typeof(DivideByZeroException))]
        public void Divide_DividesByZero_FailsToMeetContractRequirement()
        {
            const int numerator = 1;
            const int denominator = 0;
            var actual = MathematicalFunctions.DivideWithContract(numerator, denominator);
        }

Note here that if you have set up static checking ( see the code contracts tab in project properties ) - you will see that the contract checking will point out that things are going to cause problems. Be sure to do this on the calling assembly - that is the test project in my case:


When running these tests, one will get a popup saying that the contract requirements failed to be met:


By clicking ignore - the test will continue, the exception will be thrown and the test will pass. However, this is inconvenient and we can easily disable this by setting the "Runtime Checking" to "None" on the assemblies that are being called by the test.

Now - it's happy testing from this point:


Bottom line...

Obviously the contract checking is more advanced and the other two:

  1. The most important benefit is of course compile time feedback on the written code. The static contract checking. You can detect an error even before running a test or the application.
  2. It's less verbose than the IF-Exception way, because it takes up a third of the number of lines.
  3. It provides more control over the exception that will be thrown than Assertions. As far as I know, either an AssertionFailedException is thrown or not.
I cannot find any downsides at this point. Feel free to leave any feedback about aspects I might have overlooked.

Saturday, December 1, 2012

Unit testing guru: Roy Osherove

Sure, I learnt how to write unit tests in university. Writing tests to check if te result of adding two integers is actually the sum of the two. However, it took me some work experience to realize the powerfullness of unit testing. When trying to make my offshore team see how they could benefit from testing their code, my collegue found this website: the art of unit testing by Roy Osherove. He's the author of the book with the same name, which is on my to-read list. Roy is described on his blog as:
Roy Osherove is the chief scientist at Bouvet.no, and the author of The Art Of Unit Testing and Notes to a software team leader. He is also one of the original ALT.NET organizers. He consults and trains teams worldwide on the gentle art of unit testing, test-driven development and how to lead software teams. He frequently speaks at international conferences on these topics and others.
He's got hours of instruction video's and video's of his talks on his website. I see the most recent ones are talks he did on mock objects. What I find particularly interesting are his pair programming sessions - here. For instance this one:
Some of the lessons I learned from Roy:

  1. The first thing I noticed is how much attention he pays to naming methods, variables, parameters etc. etc. He is very perfectionistic about it. But I think it is because he forces himself ( and the guy he's working with ) to find the essence, the concept of the thing he is working on. 
  2. Not only make sure your code is very well readable ( maintainability ), but also make sure your tests are very intuitive and readable for the other teammembers. 
  3. ReSharper is your friend. He is a test-driven development guru and you can see him writing tests first and then take advantage of ReSharper to generate all the stuff that is not there yet. 


There is probably a lot more lessons I'll learn once I get through his hours of video's and his book. Anyway - check him out if you want to learn about Unit testing and TDD.