Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Archive for the ‘Testing’ Category

DoUNo: Setting expectations on nullable type, NMock2

without comments

Ever had a problem of setting an expectation for nullable objects?

If you wanna return false when .HasValue of a nullable object is called, then you cannot do it with the normal expect statement. Rather, try not returning any values, because NMock2 returns default value of HasValue (False) if nothing is set as return values in expect statements.

Here is a sample,

public interface IProduct  //Interface that has a nullable member
{
  int? ProductNo  //Member that I wanna test and I wish to test the scenario in which this will be null
  {
    get;
  }
}
IProduct aProduct= myMockery.NewMock<IProduct>();
//Stub.On(aProduct).GetProperty("ProductNo").Will(Return.Value(default(int?));  //this statement produces a runtime exception, so we have to use the following instead
Stub.On(aProduct).GetProperty("ProductNo");  //no return value is set, nmock2 returns false when .HasValue is queries

Hope this helped you.

Sudarsan Srinivasan
- on behalf of my friends (they found this hack :P )

Written by sudarsanyes

November 6th, 2009 at 9:08 am

Settings expectations in NMock2

without comments

One of our previous articles would have given an introduction to NMocks. In here, we will try out various methods of setting expectations when we do a unit test.

note — this article considers that you know the basics of unit testing. check out our previous article if you would like to know the basics of nmock2

In NMock2, you have a wide variety of setting expectations on mocked objects.

Stubs

Stubs are expectations whose occurrences are unknown. We use stubs when we are not sure the number of times it might be called. So generally Stubs are used when expectations needs to be set 0 or more times

Stub.On(myMockedObject).Method("GetName");  //Use this only when you are unaware of the occurrences,
                                            //otherwise you end up writing a bad UT

Expect

We use the Expect class when the number of calls to the method or property of the mock objects are known.

For example,

If number of occurrences are 7 on the method called, “GetName“, then use,

Expect.Exactly(7).On(myMockObject).Method("GetName")...

If the number of occurrence is 1 on the method called, “GetName“, then use,

Expect.Once.On(myMockObject).Method("GetName")...

or

Expect.Exactly(1).On(myMockObject).Method("GetName")...

You can even set negative expectations. For example,
If you are pretty sure that the method “GetName“, will not/should not be called in your unit test, then use,

Expect.Never.On(myMockObject).Method("GetName")...

Expectation With Parameters

If you are unit testing a method that makes a call to an interface which inturn takes two params and if you know the values of those params, you could set expectation on the mock object for the method with the known params.

For example,

If “GetName” method takes two params and if the param values are “foo” and “bar” according to the unit test case, then we can write an expectation as,

Expect.Once.On(myMockObject).Method("GetName").With("foo", "bar")...

Expectation On Events

You can add expectation on events of the mock object with the EventAdd method.

For example,

public class Foo
{
  public event EventHandler ObjectChanged;
  ...
}
public class FooBarBaz
{
  private Foo myFoo;
  ...
  private void SomeMethod()
  {
    myFoo.ObjectChanged += new EventHandler(Foo__ObjectChanged);
    ...
  }
}

If you are writing a unit test for the method SomeMethod, then you shall add an expectation of the following form,

Expect.Once.On(myMockObject).EventAdd("ObjectChanged", Is.Anything);

Expecting Exceptions

You could also expect exceprions by adding the attribute, ExpectedException on top of your unit test.

For example,

[Test(Description="Test case method that will test whether the ArgumentNullException is raised")]
[ExpectedException(typeof(ArgumentNullException))]
public void TestExceptionalScenario()
{
  ...
  //call the method that is supposed to throw the ArgumentNullException
}

These are the commonly used expectations. If you have used something really weird, I expect you share it with us     :D        :D

Written by sudarsanyes

September 3rd, 2009 at 2:24 pm

Posted in C#, Testing, unittest

Tagged with , , ,

Using NMock2 in C#

with 6 comments

As many would know, mocking is a useful and inevitable part of unit testing. The intention behind mocking of objects is to isolate the functionality of one method from its dependencies, For e.g. a method call from within the target test method being handled in an external interface.
This approach will help us focus on the unit being tested, rather than arranging for dependency invocation (which might be really complex at times).
I would like to share a basic tutorial here on mocking .net objects using NMock2 (available at http://nmock.org)

Steps to be followed are as follows.

1) Download the NMock2 package from http://nmock.org/download.html

2) Create a console application and add NMock2.dll from the downloaded package, as a reference.

3) Consider that you have a simple interface defined as follows.

public interface IPerson
{
  string GetName();
}

4) A class Hello has the following definition

class Hello
{
  IPerson person;
  //--This method invokes the interface method.
  public String Greet()
  {
    return "Hello " + person.GetName();
    //If you were to write a ut for this method (without nmocks), you should have created an
    //actual object of person and your inputs should be capable of navigating
    //thru' GetName() of Person class
  }
}

5) Our intention is to unit test the method Hello.Greet(). This is not straight forward as definition of IPerson.GetName() is not known. Moreover, it should not be of our concern when we are testing Greet() method’s functionality.

6) This is where we mock the Interface IPerson and hardcode a return value for the method GetName() so as to concentrate on the functionality of the method Greet() alone while testing. Let us see how we can do that.

7) We create a test case class, say HelloTestCases and write a method to test Greet()
i) Make use of a class named Mockery (supplied by NMock2) to create a mock object.
ii) Create a mocked interface object for IPerson using the NewMock() method.
iii) Set up a mocked result  for any method/property by hardcoding of your choice.
iv) Mock the result for one execution of the mocked method.
v) Create an object of the target test class.
vi) Invoke the target test method using the object instance created in (v) and check the results with Assert statements of NUnit.

public void Test_GreetPositive()
{
  //--i. Creating a mockery object.
  Mockery personMock = new Mockery();
  //--ii. Mocking the IPerson interface using Mockery object.
  IPerson p = personMock.NewMock<IPerson>();
  //--iii. Setting the mocked return value.
  string returnValue = "Pradeep";
  //--iv. Mocking the result for method call IPerson.GetName() method.
  Expect.Once.On(p).Method("GetName").WithNoArguments().Will(Return.Value(returnValue));
  //--v. Creating the target class object.
  Hello h = new Hello(p);
  //--vi. Invoking the target test method.
  Assert.AreEqual("Hello Pradeep",h.Greet());
}

So simple, isn’t it? This was a simple example. There is much more to add as feathers to NMock2.

NMock2 also provides a wide variety of Expectatons, like,

Expect.Once, Expect.Excatly(<number of times a method is called>), Stub (0 or many times), Expect.Never and so on. You could also expect exceptions by adding an attribute called [ExpectedException(typeof(<exception class>)] before the unit test method for the target method that throws an exception. In other words, NMocks2 is really an awesome lib to do a perfect unit  test for your libraries. Try it out and share your experiences.

Thanks! See you all soon.
Praseo

Written by praseodeveloper

August 19th, 2009 at 10:04 am

Posted in C#, Testing, unittest

Tagged with , , , ,

Doctests in Python

without comments

This post is due for a long time since my post on Singular form of a word program and here it is - Doctests in Python. From the python library reference,

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.

Doctests are an easy way to test small functions by specifying the output of the function in docstrings. In python you can (should) write docstrings for classes and methods which can be used to generate the documentation for the module. In those docstrings, you just specify calls to the function with the return string specified. The doctest module automatically asserts the output and verifies whether the test passes or fails.

Lets see an example of doctest and how to run them. Lets create a function which adds two numbers.

def add(x, y):
    """Adds two numbers/strings together

    >>> add(1,2)
    3
    >>> add('foo','bar')
    'foobar'
    """
    return x+y

Here we have written the docstrings and have four lines which look like the python shell. There we call the function with various arguments and also specify how the function will return.

So, how do we run the test? Just include these lines in the module and run the file directly. This is the usual way we run doctest (in the __main__ part of the file).

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()

You just have to call the doctest.testmod() function and it will search for all such tests in the docstrings and outputs nothing if the tests pass. If you want to get more verbose output, run the file as python filename.py -v

There are many advantages of doctests (wikipedia has a lot more):

  • Easy to understand what a function is going to do if called
  • Tests and code together - easy to update the test if code changes
  • Most of the times I execute my functions on the shell - so I just have to copy-paste the output from the shell to the code

Once you start using doctests, you would find yourself trying to use it in all possible places. For more elaborate testing, you should probably use pyunit.

Is there any other programming language which has tests written directly in the documentations? If you were to design such a testing module for you favourite language, how would you do it (especially if it doesn’t have a interactive shell)? Do explain your views on it below.

Written by cnu

August 9th, 2008 at 8:08 am

Posted in Documentation, Python, Testing

Tagged with , ,