Monday, December 21, 2015

Getting started with Unit Testing and Moq - Part 3

Part 1
Part 2
Part 3 you are here
Part 4

In the previous post we got our first tests set up with moq.  So now let’s see about creating some unit tests to go along with our WCF services.
First thing we need to do, is create our WCF service.  Nothing fancy, the default functions created with the WCF Application should suffice.
First, add a new project to the RussUnitTestSample solution:
Right click solution -> Add -> New Project...



WCF -> Wcf Service Application.  Named RussUnitTestSample.Wcf



Your newly added project should look similar to:




Next, we’ll want to configure our project to have multiple start up projects (both the console app, and the wcf service), additionally we will add the WCF service as a service reference in the console application.
Multiple startup projects.  Right click solution -> Properties




Select multiple startup projects, change the combo boxes so both the console application, and the wcf application are set to “start”




Find the port the WCF service is set to run on next.  Right click the WCF project -> properties




Copy the URL highlighted for use in the next step




Next, we’ll add the WCF project as a service reference to the console application.
In the console application, Right click “References” -> Add Service Reference...




Paste the URL copied before (localhost:portNumber/) -> Discover -> Drill into
service and select your interface (IService1)




Your project should now display a new Folder “Service References” and have the service reference listed.  Additionally notice my app.config file has been automatically checked out, as WCF endpoint information has been added.




Here is what was added to the config file




<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" />
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:23336/Service1.svc" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
            name="BasicHttpBinding_IService1" />
    </client>
</system.serviceModel>
Now our service reference is all added and ready, let’s test it!  Modify the Program.CS of the console application with:
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

Console.WriteLine("\n");
Console.WriteLine("{0}", client.GetData(42));
Console.WriteLine("\n");

Your program.cs should now look like:

namespace RussUnitTestSample
{
    class Program
    {

        #region consts
        const string CONNECTION_STRING = "Data Source=192.168.50.4,1515;Initial Catalog=MBES;Persist Security Info=True;Integrated Security=true;";
        #endregion consts

        #region Entry

        static void Main(string[] args)
        {
            GetNumbersAndAddThem obj = new GetNumbersAndAddThem(
                new DbGetSomeNumbers(new BaseDbConnection(CONNECTION_STRING)),
                new NumberFunctions()
            );

            Console.WriteLine("\n");
            Console.WriteLine(obj.Execute());
            Console.WriteLine("\n");

            ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

            Console.WriteLine("\n");
            Console.WriteLine("{0}", client.GetData(42));
            Console.WriteLine("\n");

        }

        #endregion Entry
    }
}
Give it a run and:



Now our WCF service is hosted, and successfully consumed in the console application.  Diff in previous and current can be found on GitHub, note a lot of files in the pull request are auto-generated from the WCF service.
Next, we’ll look at how to test it.

Wednesday, December 16, 2015

Getting started with Unit Testing and Moq - Part 2

Part 1
Part 2 you are here
Part 3
Part 4

In the previous post I started on a project to start learning about unit testing, specifically with moq and for WCF services. Thus far, we have only implemented basic unit tests for a piece of code with no external dependencies, which needed no mocking.
This time, I’m going to explore mocking and testing objects relying on the IDbGetSomeNumbers and INumberFunctions interfaces.
As a reminder, those interfaces and corresponding classes are defined as:

namespace RussUnitTestSample.Business.Interface
{

    /// <summary>
    /// Interface for number functions
    /// </summary>
    public interface INumberFunctions
    {
        /// <summary>
        /// Add numbers together
        /// </summary>
        /// <param name="numbers">The numbers to add.
        /// <returns>The sum</returns>
        double AddNumbers(double[] numbers);
    }

    /// <summary>
    /// Interface to get some numbers from the database
    /// </summary>
    public interface IDbGetSomeNumbers
    {

        /// <summary>
        /// Get an array of doubles from the database
        /// </summary>
        /// <returns></returns>
        double[] GetSomeNumbers();
    }
}

And the class utilizing them:

namespace RussUnitTestSample.Business
{

    /// <summary>
    /// Get numbers and then add them together
    /// </summary>
    public class GetNumbersAndAddThem
    {

        #region Private
        private readonly IDbGetSomeNumbers _dbGetSomeNumbers;
        private readonly INumberFunctions _numberFunctions;
        #endregion Private

        #region ctor

        /// <summary>
        /// Constructor - provide dependencies
        /// </summary>
        /// <param name="dbGetSomeNumbers">THe IDbGetSomeNumbers implementation.
        /// <param name="numberFunctions">The INumberFunctions implementation.
        public GetNumbersAndAddThem(IDbGetSomeNumbers dbGetSomeNumbers, INumberFunctions numberFunctions)
        {
            if (dbGetSomeNumbers == null)
                throw new ArgumentNullException(nameof(dbGetSomeNumbers));

            if (numberFunctions == null)
                throw new ArgumentNullException(nameof(numberFunctions));

            this._dbGetSomeNumbers = dbGetSomeNumbers;
            this._numberFunctions = numberFunctions;
        }

        #endregion ctor

        #region Public methods

        /// <summary>
        /// Get the numbers and add them.
        /// </summary>
        /// <returns></returns>
        public double Execute()
        {
            var numbers = _dbGetSomeNumbers.GetSomeNumbers();

            return _numberFunctions.AddNumbers(numbers);
        }

        #endregion Public methods

    }

}

In the constructor, I'm taking in an implementation of both IDbGetSomeNumbers and INumberFunctions.  I am doing this, as they are not dependecies for the functionality of the class, and as such their implementation is not important.  Rather, it is important, but not for the testing of this class.  As the unit testing definition stated:

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation.

So the interface implementations do need testing (which was already done), they however do not need testing from GetNumbersAndAddThems concern. The only thing that needs testing from this concern, are that the class is constructed properly, and that Execute "gets numbers from the db" and then "adds them".
Since I'm using the class constructor to take in the class dependencies:

/// <summary>
/// Constructor - provide dependencies
/// </summary>
/// <param name="dbGetSomeNumbers">THe IDbGetSomeNumbers implementation.
/// <param name="numberFunctions">The INumberFunctions implementation.
public GetNumbersAndAddThem(IDbGetSomeNumbers dbGetSomeNumbers, INumberFunctions numberFunctions)
{
    if (dbGetSomeNumbers == null)
        throw new ArgumentNullException(nameof(dbGetSomeNumbers));

    if (numberFunctions == null)
        throw new ArgumentNullException(nameof(numberFunctions));

    this._dbGetSomeNumbers = dbGetSomeNumbers;
    this._numberFunctions = numberFunctions;
}

The first things we can test for are that dbGetSomeNumbers and numberFunctions are not null.  This can be accomplished as such:

/// <summary>
/// Ensure ArgumentNullException thrown when no IDbGetSomeNumbers implementation is provided
/// </summary>
[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void GetNumbersAndAddThem_Constructor_NullIDbGetSomeNumbers()
{
    // Arrange / Act / Assert
    GetNumbersAndAddThem obj = new GetNumbersAndAddThem(null, _mockNumberFunctions.Object);
}

/// <summary>
/// Ensure ArgumentNullException thrown when no NumberFunction implementation is provided
/// </summary>
[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void GetNumbersAndAddThem_Constructor_NullNumberFunctions()
{
    // Arranage / Act / Assert
    GetNumbersAndAddThem obj = new GetNumbersAndAddThem(_mockIDbGetSomeNumbers.Object, null);
}

Now for testing Execute we can finally get to Moq!  Mocking goes hand in hand with unit testing, as one definition of mocking states:
It is difficult to test error conditions and exceptions with live, system-level tests. By replacing system components with mock objects, it is possible to simulate error conditions within the unit test. An example is when the business logic handles a Database Full exception that is thrown by a dependent service.
So because the implementation of IDbGetSomeNumbers and INumberFunctions do not matter, we would not want to (necessarily) use their real implementations. This is because they could potentially impact the system or data, which we wouldn't want to do, as we plan on running these tests at every build... and editing application data at every build would be... bad. Anyway, with mocking we can tell the interfaces upon being invoked, to return a specific response. This means we can make the Execute functionality use completely mocked implementations of their dependencies, just test the the function Execute takes in and passes back the appropriate types of values.
Mocking setup:

/// <summary>
/// Unit tests for GetNumbersAndAddThem
/// </summary>
[TestClass]
[ExcludeFromCodeCoverage]
public class GetNumbersAndAddThemTests
{

  #region Private
  Mock<inumberfunctions> _mockNumberFunctions;
  Mock<idbgetsomenumbers> _mockIDbGetSomeNumbers;
  #endregion Private

  #region Public methods

  /// <summary>
  /// Setup mock objects
  /// </summary>
  [TestInitialize]
  public void Setup()
  {
      _mockNumberFunctions = new Mock<inumberfunctions>();
      _mockIDbGetSomeNumbers = new Mock<idbgetsomenumbers>();
  }

}

The fields _mockNumberFunctions and _mockIDbGetSomeNumbers are set up as Mock<interface>.  In Setup we're just simply newing them up.  Now to the good parts, the tests utilizing the mocks:

/// <summary>
/// Tests that GetNumbersAndAddThem.Execute gets numbers and then adds them.
/// </summary>
[TestMethod]
public void GetNumbersAndAddThem_Execute()
{
    // Arrange
    double[] numbersToUse = { 1, 2, 3, 4, 5 };
    double expected = numbersToUse.Sum();

    _mockIDbGetSomeNumbers.Setup(s => s.GetSomeNumbers()).Returns(numbersToUse);
    _mockNumberFunctions.Setup(s => s.AddNumbers(It.IsAny<double>())).Returns(expected);

    GetNumbersAndAddThem obj = new GetNumbersAndAddThem(_mockIDbGetSomeNumbers.Object, _mockNumberFunctions.Object);

    // Act
    var result = obj.Execute();

    // Assert
    Assert.AreEqual(expected, result);
}

In _mockIDbGetSomeNumbers.Setup(...).Returns(...) We're stating that when the GetSomeNumbers() function is called, it needs to return numbersToUse.  Pretty fancy!  Rather than relying on our concrete implementation of IDbGetSomeNumbers which has to go out to the database, we're telling it to use this defined list of numbers that have been spelled out by the setup of the mock.  Now we can with absolute certainty say what the sum of the numbersToUse will be, because we know what numbers will be provided each time since they aren't being pulled from the database.
Hopefully that all makes sense. Makes sense to me anyway! :O
Next time I hope to get into WCF creation and testing.
I'm trying out tumblr now... not sure if I like it.  I do enjoy the markdown editor, but it doesn't really seem suited for longer posts.  http://rhammett.tumblr.com/

Maybe I'll switch back to here and continue not posting anything.

Monday, November 30, 2015

Getting started with Unit Testing and Moq

Part 1 you are here
Part 2
Part 3
Part 4

We had a new team lead start recently, he seems to have had a fair amount of experience in areas I'm only vaguely familiar with, mostly through reading.  One of the first things being pushed for is a concentration on unit testing.  While I did begin implementing some tests into our codebase a few months ago (around 250 so far), I feel that there's still a long way to go.  Luckily Chris is here to help impart knowledge to us, hooray!

So getting started with unit testing - first it should be defined what a unit test is from https://en.wikipedia.org/wiki/Unit_testing :

In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use.
Given the following classes/methods:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
namespace RussUnitTestSample.Business.Interface
{

    /// <summary>
    /// Interface to get some numbers from the database
    /// </summary>
    public interface IDbGetSomeNumbers
    {

        /// <summary>
        /// Get an array of doubles from the database
        /// </summary>
        /// <returns></returns>
        double[] GetSomeNumbers();
    }

    /// <summary>
    /// Interface for number functions
    /// </summary>
    public interface INumberFunctions
    {
        /// <summary>
        /// Add numbers together
        /// </summary>
        /// <param name="numbers">The numbers to add.</param>
        /// <returns>The sum</returns>
        double AddNumbers(double[] numbers);
    }
}

namespace RussUnitTestSample.Business
{

    /// <summary>
    /// Get numbers and then add them together
    /// </summary>
    public class GetNumbersAndAddThem
    {

        #region Private
        private readonly IDbGetSomeNumbers _dbGetSomeNumbers;
        private readonly INumberFunctions _numberFunctions;
        #endregion Private

        #region ctor

        /// <summary>
        /// Constructor - provide dependencies
        /// </summary>
        /// <param name="dbGetSomeNumbers">THe IDbGetSomeNumbers implementation.</param>
        /// <param name="numberFunctions">The INumberFunctions implementation.</param>
        public GetNumbersAndAddThem(IDbGetSomeNumbers dbGetSomeNumbers, INumberFunctions numberFunctions)
        {
            if (dbGetSomeNumbers == null)
                throw new ArgumentNullException(nameof(dbGetSomeNumbers));

            if (numberFunctions == null)
                throw new ArgumentNullException(nameof(numberFunctions));

            this._dbGetSomeNumbers = dbGetSomeNumbers;
            this._numberFunctions = numberFunctions;
        }

        #endregion ctor

        #region Public methods

        /// <summary>
        /// Get the numbers and add them.
        /// </summary>
        /// <returns></returns>
        public double Execute()
        {
            var numbers = _dbGetSomeNumbers.GetSomeNumbers();

            return _numberFunctions.AddNumbers(numbers);
        }

        #endregion Public methods

    }

}


Note in the above, I am using interfaces to allow for the injection of dependencies (an important part of unit testing with mocks, and in general).  The basic idea is you provide sample (unimportant) implementations to the dependent pieces of the whole, the pieces that are not currently being tested, therefore are unimportant to the test - at least when testing the "Put it all together" methods.

I see the following things that need to be tested - there could very well be more, but here it is at a glance:

    INumberFunctions.AddNumbers
    IDbGetSomeNumbers.GetSomeNumbers
    GetNumbersAndAddThem.Execute

There are a few other stragglers in there that will become apparent (if they aren't already) like null testing parameters in the constructor, testing empty array for add numbers, etc.

For INumbersFunctions.AddNumbers, we need to of course, check the numbers are being added properly.  I have accomplished that with the following tests:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RussUnitTestSample.Business.Tests
{
    [TestClass]
    [ExcludeFromCodeCoverage]
    public class NumberFunctionTests
    {

        #region Public methods

        /// <summary>
        /// Test exception thrown when numbers provided is null
        /// </summary>
        [ExpectedException(typeof(ArgumentNullException))]
        [TestMethod]
        public void AddNumbers_NullParameterNumbers()
        {
            // Arrange / Act / Assert
            NumberFunctions nf = new NumberFunctions();
            var result = nf.AddNumbers(null);
        }

        /// <summary>
        /// Test exception thrown when 0 numbers provided in array
        /// </summary>
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void AddNumbers_EmptyArrayNumbers()
        {
            // Arrange / Act / Assert
            NumberFunctions nf = new NumberFunctions();
            var result = nf.AddNumbers(new double[] { });
        }

        /// <summary>
        /// Add two positive numbers
        /// </summary>
        [TestMethod]
        public void AddNumbers_TwoNumbers()
        {
            // Arrange
            double[] numbers = { 1, 2 };
            NumberFunctions nf = new NumberFunctions();

            // Act
            var result = nf.AddNumbers(numbers);

            // Assert
            Assert.AreEqual(numbers.Sum(), result);
        }

        /// <summary>
        /// Add 10 numbers mixed positive and negative
        /// </summary>
        [TestMethod]
        public void AddNumbers_TenNumbersWithPositiveAndNegatives()
        {
            // Arrange
            double[] numbers = { 1, -2, 3, 4, -5, 6, 7, -8, 9, 10 };
            NumberFunctions nf = new NumberFunctions();

            // Act
            var result = nf.AddNumbers(numbers);

            // Assert
            Assert.AreEqual(numbers.Sum(), result);
        }

        [TestMethod]
        public void AddNumbers_ProvideOneNumber()
        {
            // Arrange
            double[] numbers = { 1 };
            NumberFunctions nf = new NumberFunctions();

            // Act
            var result = nf.AddNumbers(numbers);

            // Assert
            Assert.AreEqual(numbers.Sum(), result);
        }
        
        #endregion Public methods
    }
}

There is most definitely some overlap in some of the tests, but with something so simple there's still quite a few!  I don't feel the actual implementation of NumberFunctions is important, as I'm concentrating on the tests.

That takes care of the class that has completed non Moqed tests.  In the next post (which I will hopefully do soon) I'll go into how I accomplished my first unit tests with Moq.  If I can get a well enough cadence going on, I hope to cover Moqing WCF service calls - as that's what we use at work for our communication to our DB, so being able to moq that as well would be beneficial.

Full code including the Moq unit tests can be found at: https://github.com/Kritner/RussUnitTestSample



Sunday, August 23, 2015

Movin on up and trying to stay relevant.

Kristen and I are building a house in Westminster, and should be moving sometime around mid October!  We're both now in our 30s, and currently have no kids.  The house we're building is 4 bedroom, 2.5 bath, an open first floor, and lots of unfinished basement. We do have 4 bedrooms, so hopefully the baby will come sometime in the near future, we're starting to get old!

We've been at our current house in Owings Mills for about 6 years, and unfortunately we do not have enough equity in the house to be able to afford to sell at this point.  We're not underwater, but after fees, closing cost assistance, etc, we would most likely have to pay out a chunk of change we just can't handle with the new house.  I really hope we're not making a mistake by buying our dream house in a great neighborhood prematurely.  We plan on using a management company to rent out our house in Owings Mills.  After the companies fees, we'll practically be breaking even with the mortgage.  The budget is in no danger as long as we can place renters, but it will be (quite) tight without them.

We'll likely be setting up a meeting with a financial advisor at some point soon, to hopefully help get us on track as far as insurance, retirement, saving, etc.  In addition to the financial advisor we'll likely need to get a tax person, as we'll now be landlords - which sounds like it can complicate taxes significantly.

My commute is getting longer in the move, but I don't mind that so much.  I somewhat enjoy driving, and it will give me a chance to listen to more podcasts.  I've somewhat fallen off the wagon when it comes to my exercise, so the 2x longer commute could be problematic for getting back on.  I'm really hoping I'll manage to get into the habit of waking up earlier than I currently do, to get back into my routine - something I'll definitely need to do when we have kids.

I'm enjoying my job at DCCA, and I feel that I have the skills necessary to do my job.  However, I still feel like I am behind when I look at the careers of many of the .net guys whose podcasts I listen too.  My handle on backend is mostly solid, and I can get done what I need to get done on the front end.  Brownfield application development seems pretty solid, but it's the new stuff, with all of the new frontend tech that I'm not sure how to get my foot in the door.  I'm not sure what exactly I think I could do in the long run for my career, but I do enjoy helping people and teaching, it's too bad I'm just so anxious around unfamiliar (and sometime familiar) people. :/

I'd like to start learning about angular, MVC, mobile, windows dev, etc, but I'm not exactly sure where to start.  I've subscribed to Pluralsight and am going through courses when I have time, (though that time has been limited lately with prepping for the move) but that is very different than actually developing.  My StackOverflow reputation has been on the steady increase, which I'm doing for a few reasons.  I believe that answering the questions will help my resume, I enjoy helping people, and it helps me actually learn a bit - I would like to do more though.  To really get into learning the new things that I'd like to learn, I want to start get into contributing into open source projects.  I'm having problems finding something that isn't way above my head, so maybe I'll start with some tutorial apps for now.

I probably won't update this again for a while, but maybe blogging about... something... will help me in the long run; be it from getting some of my feelings out there, or (hopefully) something useful to the programming community - my peoples!

Wednesday, January 21, 2015

And it's like... what's the deal with build servers?

So what is a build server?

The simplest way I can think of to explain a build server is to imagine hiring a brand new developer for each code check in, giving them explicit instructions to accomplish the build, and letting them go.  Maybe that requires a bit of explanation - the idea of a build server is to provide a reproducible set of instructions/steps to accomplish building your application from start to finish without requiring additional input from the developer checking in the code.

Why do I need one?

As a developer without a build server, you might be in a situation where you have a project that builds perfectly fine locally, but when another developer attempts to build your latest bits, you encounter compile errors as far as the eyes can see. I unfortunately have experienced such a situation for each project I have pulled from source control (in instances where a build server was not used) - not that I fault the organization, persons, or projects involved - if you don't know better, you don't know better.

Once you do know about build servers, I do feel it is important to implement one if at all possible, as they are relatively easy to configure, and once done, an inordinate amount of time can be saved across developers.

Why doesn't everyone use a build server?

I only really see two reasons to not utilize a build server... and one is more of an excuse than a reason.  The first reason was mentioned above, if you don't know about a build server process, then you likely wouldn't have one.  The second reason (the excuse) - would be thinking it's "too hard" or "not worth it" to set up.  If the build server is too hard to set up, that likely means your manual build process is quite complex, and could likely benefit *more* from a build server than a simple application.  If grabbing a project from source control for the first time gives you a nice 10-15+ errors, which can take anywhere from 5 minutes, to several hours to resolve - and involve several developers - then you really need to think about what needs to be changed in order to fix that.  

Are there external libraries being utilized that need to be added to source?  Are there several SDKs missing from the developers machine required to build?  Did I miss something in check in that would not allow the next developer to build? All of those questions can be quite difficult to deduce when building locally.  With a build server, it's like a *separate* developer working on a project for the first time, every time, at every check in.  

If some new dependency is added to the project and is missed in the check in, the build server will immediately report failure and the developer (could) be notified as such, and actions can be taken to correct.  Without a build server, it could be quite the mystery as to why a project all of a sudden won't build, or why a project will not build for the first time.  

So why don't you have a build server yet?  

How do I set one up?

There are lots of tutorials on ( setting up build servers, and there are lots of build servers even! The build server I use on my personal site is TFS Build Service/MS Build I think the tutorial I referenced was: https://msdn.microsoft.com/en-us/library/ms181712.aspx

Other build servers include (but are not limited too):
etc

What's next? What else can I do with a build server?

Having a build server gets you and/or your organization a lot of benefit, but in my opinion, one of the best benefits is the ability to implement automated deployment.  Once a build is completed, steps can be taken in a number of ways which can vary greatly dependent on project complexity, your project's bits can be deployed to your next environment, AUTOMAGICALLY.