In previous articles, we discussed the classification of application testing and unit testing grounds. We also introduced mock objects and stubs. Today’s article was a challenge for me personally to describe the frameworks to support testing. At the beginning of the explanation, however, we will go in depth into mocks, and only then proceed to the frameworks. Of course, no one is able to describe them all, so I chose the four frameworks that are used every day. Some of them are easy to use, and some of them are really combined to create tests.

Today we will learn to use them and know their advantages and disadvantages. We will learn the three frameworks: Pex, NMock, and Rhino Mocks. So, you ready? What will we begin with? So we’re going to test frameworks. Note! All of the examples in this article will benefit, not eclipse Microsoft Visual Studio.

Mocks again

Let’s begin with mocks. It is a matter of reminding the basic information about them. A mock is really an abstraction of objects or classes, whose task is to effectively isolate the classes, in order to investigate and ensure the appropriate level of verification tests.

Take an example of a data management database. If your class has to use them, and does not want to create the data layer class to support them because of the time that we spend on creating a wrapper for MySQL, create a mock that simulates the retrieved data. In this way we do not need to configure anything or even think about how to write.

We write simply a dummy class and specify the manner in which the target class should behave. Then we simply write tests for the target class. These tests are created based on the expected behavior of the class, which is now a mock. It is one of the solutions that effectively separates all types of classes from each other and at the same time makes the whole process of software development and testing much more pleasant than usual.

So what is really a mock? A mock object is a model of research, which usually is used for research and testing of various interfaces. And so it is ideal for testing and determining the functionality of the individual because the interfaces are mainly used for separating the individual functions from each other. This saves the time that we spend on the implementation of the working classes of data on the interface.

When writing a mock we need to know one thing. First, we must always check the expectations that we have relative to the functionality, then we should check whether the class meets our expectations. A mock is used mostly for classes, where the survey is difficult for some reason. Sometimes mock objects also apply to references to external resources such as web services and databases. Mostly they are solutions that perform too slowly for there to be any point in writing unit tests for them.

An example in which we operate

I want to show you a simple example with which we operate in our project. This example will be based on mock objects and because of it I hope that I can fully convey to you the difference between mocks and stubs. So let’s begin:

First, let’s create a new project in Visual Studio called Examples.

Second, in ConnectionProvider create a class with the following content:

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

using System.Diagnostics;

using System.Net.NetworkInformation;

namespace Examples2

{

public class ConnectionProvider

{

public bool IsOnline (string address) {

Debug.Assert (! String.IsNullOrEmpty (address));

using (Ping ping = new Ping ()) {

PingReply pingReply = ping.Send (address);

if (pingReply.Status == IPStatus.Success) {

return true;

}

}

return false;

}

}

}


Third, create a class CheckServer, which will be tested:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

namespace Examples2

{

class CheckServer

{

public bool IsOnline (string address)

{

Debug.Assert (! String.IsNullOrEmpty (address));

ConnectionProvider ConnectionProvider connectionProvider = new ();

connectionProvider.IsOnline return (address);

}

}

}



Fourth, add a test method CheckServer:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Examples.UT

{

[TestClass]

class CheckServerTest

{

[TestMethod]

public void IsOnlineTest ()

{

CheckServerTest CheckServerTest target = new ();

string address = "google.com";

excepted bool = true;

bool actual;

actual = target.IsOnline (address);

Assert.AreEqual (expected, actual);

}

}

}


Fifth, run the test.

We created our first special test. Isn’t that great? Maybe you want to practice a bit on it? I will suggest two changes for you:

First, our dear customer has changed their requirements. Please, you must run an actualization test to check for availability of the host http://resources.infosecintitute.com

Second, again the customer changed their requirements. Now you have to check the address http://microsoft.com

Ok it was not even a mock, but we can be proud of ourselves. Now you want to write something again, right? Let’s get to the end of the first mock. At the same project:

First, in ConnectionProviderEx create a class. Here’s the code:

using System.Text;

using System.Diagnostics;

using System.Net.NetworkInformation;

namespace Examples2

{

public interface IConnectionProviderEx

{

IsOnline bool (string address);

}

ConnectionProviderEx class: IConnectionProviderEx

{

public void IsOnline (string address)

{

Debug.Assert (! String.IsNullOrEmpty (address));

using (Ping ping = new Ping ());

PingReply reply = ping.Send (address);

if (Reply.Status == IPStatus.Success)

{

return true;

}

return false;

}

}

}


Second, create a class in ChecServerEx. What in this case, should you pay attention to? You must note that in this case ConnectionProviderEx class is not created inside the method IsOnline, instead the instance is injected into the constructor as CheckServerEx IConnectionProviderEx interface. Here’s the code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

namespace Examples2

{

class CheckServerEx

{

connectionProvider_ IConnectionProviderEx private readonly;

public CheckServerEx (IConnectionProviderEx connectionProvider)

{

connectionProvider_ = connectionProvider;

}

public bool IsOnline (string address)

{

Debug.Assert (! String.IsNullOrEmpty (address));

connectionProvider_.IsOnline return (address);

}

}

}


Third, now let’s test methods CheckServerEx.IsOnline:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Example.UT

{

[TestClass]

class CheckServerExTest2

{

[TestMethod]

public void IsOnlineTest ()

{

IConnectionProviderEx IConnectionProviderEx connectionProvider = new ();

CheckServerEx target = new CheckServerEx (connectionProvider);

string address = "example.server.test";

excepted bool = true;

bool actual;

actual = target.IsOnline (address);

Assert.AreEqaul (excepted, actual);

}

}

}


Fourth, run this test. Check that the test is not passed, since the class that we are testing has a huge dependence on the remote machine.

Fifth, add a class to the project StubConnectionProviderEx Examples.UT tests. This class implements the same interface as the class ConnectionProviderEx:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Examples.UT

{

internal class StubConnectionProviderEx: IConnectionProviderEx

{

public bool Online (get, set,);

public bool IsOnline (string address) {

Online return;

}

}

}


Sixth, now it’s time to update CheckServerExTest.IsOnline to use the type of object you create:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Example.UT

{

[TestClass]

class CheckServerExTest2

{

[TestMethod]

public void IsOnlineTest ()

{

IConnectionProviderEx connectionProvider = new StubConnectionProviderEx (

Online = true;

);

CheckServerEx target = new CheckServerEx (connectionProvider);

string address = "example.server.test";

excepted bool = true;

bool actual;

actual = target.IsOnline (address);

Assert.AreEqaul (excepted, actual);

}

}

}


Seventh, now run the test to make sure it works. Consider why?

In this way we have created our first mock. True, it is not difficult? Now you can go to the frameworks.

NMock3 or start creating mocks object

“NMock3 builds on the work of NMock2. Specifically it adds lambda expressions to the matcher syntax. You can use lambda expressions instead of strings, making refactoring possible. The idea of Syntactic Sugar is maintained in all expectations that read like an English sentence.”

Source: http://nmock3.codeplex.com/

About the framework will not be much to write about. It is neither nice nor friendly. And yet you use it to also create a test. So let’s start at the points:

First, add UT.Examples to a project for the library NMock3 references.

Want to learn more?? The InfoSec Institute Ethical Hacking course goes in-depth into the techniques used by malicious, black hat hackers with attention getting lectures and hands-on lab exercises. While these hacking skills can be used for malicious purposes, this class teaches you how to use the same hacking techniques to perform a white-hat, ethical hack, on your organization. You leave with the ability to quantitatively assess and measure threats to information assets; and discover where your organization is most vulnerable to black hat hackers. Some features of this course include:

  • Dual Certification - CEH and CPT
  • 5 days of Intensive Hands-On Labs
  • Expert Instruction
  • CTF exercises in the evening
  • Most up-to-date proprietary courseware available

Second, add a new test IsOnlineTest_NMock3:

namespace Examples.UT

{

[TestClass]

class CheckServerExTest

{

[TestMethod]

public void IsOnlineTest_NMock3 () {

string address = "google.com";

excepted bool = true;

bool actual;

MockFactory MockFactory mockFactory = new ();

var = mockFactory.CreateMock <IConnectionProviderEx> connectionProviderStub (MockStyle.Stub);

connectionProviderStub.Expects.AtLeast (0). MethodWith (_ => _.IsOnline (address)). WillReturn (true);

IConnectionProviderEx connectionProvider = connectionProviderStub.MockObject;

CheckServerEx target = new CheckServerEx (connectionProvider);

actual = target.IsOnline (address);

Assert.AreEqual (expected, actual);

}

}

}


Third, you must note that you should always add “using NMock” to mock the factory that was available.

Fourth, fire up the test, I’m sure will pass.

Pex and Moles, the most interesting of the frameworks for the Net

Pex is the first framework that will be discussed here. It is one of the best tools for testing applications in Visual Studio. It is used to perform automated testing by Whitebox. It is primarily used by applications with NET environment. It was developed by Microsoft in addition to the Visual Studio environment. Pex can be downloaded from http://research.microsoft.com/en-us/projects/pex/downloads.aspx.

Pex can generate tests automatically from the machine that can no longer cover the entire code, known as automated testing. Pex has one major advantage: if Pex finds any potential errors in the code, it suggests how to alter them. This is one of the best features of the service.

Pex also has another interesting feature, namely, Pex is able to perform a complete analysis of the code by searching for boundary conditions and generating test cases. The tool also automatically finds errors and allows you to greatly reduce the maintenance costs of code. Currently Pex and Moles are a total of one tool for creating mocks.

Moles and Pex Installation:

First, if your system does not yet contain Moles and Pex, download and install them.

Second, create a new test project UT.Examples.

Third, look for references to the test project Examples.

Fourth, right-click on the reference from the context menu, select “Add Moles Assembly”. If this option is not available, go back to the first point.

Fifth, you must now rebuild the project Examples.UT.

Sixth you probably noticed in the reference branch, a new reference called “Examples.Moles”. It contains all the implementations of stub objects that are associated with classes Examples project.

Seventh, add a new test IsOnlineTest_MolesStub with the following content:

using System;

<strong></strong>

<strong>using Examples.Moles;
 </strong>

<strong>using Microsoft.VisualStudio.TestTools.UnitTesting;
 </strong>

<strong>namespace Examples.UT
 </strong>

<strong>{
 </strong>

<strong>    [TestClass]
 </strong>

<strong>    public class CheckServerExTest
 </strong>

<strong>    {
 </strong>

<strong>        [TestMethod]
 </strong>

<strong>        public void IsOnlineTest_MolesStub () {
 </strong>

<strong>            IConnectionProviderEx connectionProvider = new SIConnectionProviderEx {
 </strong>

<strong>                IsOnlineString = _ =>. True
 </strong>

<strong>            };
 </strong>

<strong>            CheckServerEx target = new CheckServerEx (connectionProvider);
 </strong>

<strong>            string example = "google.com";
 </strong>

<strong>            excepted bool = true;
 </strong>

<strong>            bool actual;
 </strong>

<strong>            actual = target.IsOnline (address);
 </strong>

<strong>            Assert.AreEquals (excepted, actual);
 </strong>

<strong>        }
 </strong>

<strong>    }
 </strong>

<strong>}


Eighth, as you probably noticed, adding “using Examples.Moles” to a specific class type SIConnectionProviderEx was available.

Ninth now you can run the test. It is true that it is not too complex?

Well, we described our first test using Moles. The subject, as you see, really is very developed and very complex, and at the same time is very interesting. I hope you enjoyed this introduction to the testing environment Net.

Watch out, though Moles and Pex are your requirements, here they are, taken from Microsoft:

  • You must have .NET Framework version 3.5 or later
  • You must have installed Visual Studio 2008 or Visual Studio 2008 Team System
  • You may also have installed Visual Studio 2010 environment

Of course, the use of Pex or Moles is also a choice. It may happen that you do not have Visual Studio and. NET Framework. Then you can use Pex and Moles on the command line of your operating system. Moles and Pex, despite its unusual requirements, are really not worth it to command, because they are too difficult to use. Soon we will know the real combination.

Want to learn more?? The InfoSec Institute Ethical Hacking course goes in-depth into the techniques used by malicious, black hat hackers with attention getting lectures and hands-on lab exercises. While these hacking skills can be used for malicious purposes, this class teaches you how to use the same hacking techniques to perform a white-hat, ethical hack, on your organization. You leave with the ability to quantitatively assess and measure threats to information assets; and discover where your organization is most vulnerable to black hat hackers. Some features of this course include:

  • Dual Certification - CEH and CPT
  • 5 days of Intensive Hands-On Labs
  • Expert Instruction
  • CTF exercises in the evening
  • Most up-to-date proprietary courseware available

RhinoMocks, the white rhino of frameworks for testing

I remember how I learned to program using the methodology of TDD (Test Driven Development). When using TDD methodology is very important that the system that we studyis tested in complete isolation. And that’s when I learned to create mocks and stubs. I wanted always to the complete isolation of the system, so that nothing was able to falsify test results. I also needed to be able to simulate some parts of the system. It was then that I met Rhino.

Rhino Mock creates a dynamic dummy for each .NET object. Its main objective is to help the poor developers to create fake implementations of objects and create test interactions between them, and then test them individually. Rhino Mocks can be downloaded from the http://hibernatingrhinos.com/open-source/rhino-mocks.

Now is the time, for example, to create tests using Rhino. Let’s use it for the same test. Here are the steps you need to take:

First, for a project we need to add references Examples.UT library RhinoMocks.dll.

Second, we add to our quality of testing a new test, IsOnlineTest_Rhino:

       

[TestMethod]

<strong></strong>

<strong>        public void IsOnlineTest_Rhino () {
 </strong>

<strong>            adress string = "google.com";
 </strong>

<strong>            connectionProvider var = MockRepository.GenerateStub <IConnnectionProviderEx> ();
 </strong>

<strong>            connectionProvider.Stub (c => c.IsOnline (address). Return (true);
 </strong>

<strong>            CheckServerExTest target = new CheckServerEx (connectionProvider);
 </strong>

<strong>            excepted bool = true;
 </strong>

<strong>            bool actual;
 </strong>

<strong>            actual = target.IsOnline (address);
 </strong>

<strong>            Assert.AreEqual (excepted, actual);
 </strong>

<strong>        }


Third, as you probably noticed, add a reference “using Rhino.Mocks”.

Fourth, now you can safely run the test.

As you can see, Rhino Mocks is another PHP framework for unit testing, which should be used. If you visit a page http://ayende.com/blog/4838/hibernating-rhinos-webcasts , you will find a lot more opportunities this framework. I personally honestly recommend it.

Summary

In total, we’ve covered all the most necessary frameworks. I hope that the examples in the code were not overwhelming. I promise that the next article will discuss Selenium alone, it will be a much lighter subject and you will not feel too overwhelmed by all this. Thanks for your attention.