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.