0% found this document useful (0 votes)
5 views14 pages

TDD in C#: Client Management System

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

TDD in C#: Client Management System

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming using C# Case Study

11.12 Using Test Driven Development and Extending the System


We now have a working system – though two important methods have yet to be created. We need a method to increase
a client’s credit – this should be placed within the Client class. We also need a method to delete a client, as this means
removing them from the client book. This should be placed in the ClientBook class.

It has been decided to use Test Driven Development to extend the system by providing this functionality (as discussed
in Chapter 10 Agile Programming).

In TDD we must :-
1) Write tests
2) Set up automated unit testing, which fails because the classes haven’t yet been written!
3) Write the classes so the tests pass

After creating these methods we must then adapt the interface so that this will invoke these methods.

To do this we will create two test fixtures… one to test the ClientBook class and one to test the Client class.

In the Client text fixture we will initialise a test by setting up a specified client. We will then create a test to test credit can
be added and finally we will set the TestCleanup() method to remove the client specified.

KOLON | Foto: Dag Magne Søyland | 102647

Young professionals
at ExxonMobil
Bright minds equal a brighter future.

We need your
energy to help
Please click the advert

us fuel the world

Find out
more
[Link]

Brands of ExxonMobil

Download free ebooks at [Link]

241
Object Oriented Programming using C# Case Study

The code for this is shown below…

namespace MessageManagerTests
{
TestClass]
public class TestFixture_ClientTests
{

private [Link] c;

[TestInitialize]
public void TestInitialize()
{
c = new [Link](“Simon”,
“Room 1234”, “x200”, 10);
}

[TestCleanup]
public void TestCleanup()
{
c = null;
}

[TestMethod]
public void IncreaseCredit_TestAdd5UnitsOfCredit
_
CreditShouldBe15()
{
[Link](5);
[Link](15, [Link], “Credit after adding 5
units is not as expected. Expected: 15 Actual:
“+[Link]);
}

}
}

This test creates a client with 10 units of credit, adds an additional 5 units of credit and then checks that this client has
15 units of credit.

One test does alone not sufficiently prove that the IncreaseCredit() method will always work so we may need to define
additional tests.

We also need to create test cases to test the DeleteClient() method in the ClientBook class. As this is a separate class we
need to create a new test fixture appropriately named and we need to set up a test to test this method.

Download free ebooks at [Link]

242
Object Oriented Programming using C# Case Study

The code for this is shown below….

namespace MessageManagerTests
{
[TestClass]
public class TestFixture_ClientBookTests
{
public TestFixture_ClientBookTests()
{
}

private [Link] cb;

[TestInitialize]
public void TestInitialize()
{
cb = new [Link]();

[TestCleanup]
public void TestCleanup()
{
cb = null;
}

[TestMethod]
public void GetClient_TestDeleteClient
_ShouldNotGenerateException()
{
[Link] c = new
[Link]
(“Simon”, “Room 1234”, “x200”, 10);
try
{
[Link](1, c);
[Link](1);

}
catch
([Link])
{
[Link](“UnknownClient exception should not be
thrown if client exists”);
}
}

One test we should perform on the DeleteClient() method is to test that it can delete a client … or at least not generate
an exception. The test above proves and exception is not thrown inappropriately but it does not demonstrate that the
client has been successfully deleted nor does it test what happens if we try to delete a client thqat does not exist… clearly
we need to define some more tests.

Having created appropriate test cases our code will generate complier errors as the methods IncreaseCredit() and
DeleteClient() do not exist.

Download free ebooks at [Link]

243
Object Oriented Programming using C# Case Study

We must now add these methods o our program and revise them until these tests pass.

The IncreaseCredit() method is given below…

public void IncreaseCredit(int extraCredit)


{
credit = credit + extraCredit;
}

And the DeleteClient() method is given below…

public void DeleteClient(int clientID)


{
if([Link](clientID)==false)
{
throw new
UnknownClientException(“[Link]():
unknown client ID:” + clientID);
}
}

Finally we must amend the system GUI to invoke these methods as required.

Theory suggests that TDD leads to simple code.

In this case by focusing our minds on what the IncreaseCredit() and DeleteClient() methods needs to achieve we reduce
the risk of over complicating the code. Of course we may need a range of test cases to make sure the method has all of
the essential functionality it needs.

Even if not developing our system using TDD we should define a wide ranging set of test cases for all of the classes within
the system. This will ensure that we can undertake regression testing every time we enhance or adapt the system to meet
the future and ever changing needs of the client.

Download free ebooks at [Link]

244
Object Oriented Programming using C# Case Study

Some more tests for the ClientBook class are shown below….

[TestMethod]
public void AddClient_TestAddingClient_ShouldNotGenerateException()
{
[Link] c = new
[Link](“Simon”,
“Room 1234”, “x200”, 10);
try
{
[Link](1, c);
}
catch
([Link])
{
[Link](“ClientAlreadyExists exception should not be
thrown for new clients”);
}

[TestMethod]
public void AddClient_TestAddClientTwice_ShouldGenerateException()
{
[Link] c = new
[Link](“Simon”,
“Room 1234”, “x200”, 10);
try
{
[Link](1, c);
[Link](1, c);
[Link](“ClientAlreadyExists exception should be thrown
if client added twice”);
}
catch
([Link])
{
}
}

[TestMethod] [ExpectedException(typeof([Link].
ClientAlreadyExistsException))]
public void AddClient_TestClientTwice_AlternativeVersion()
{
[Link] c = new
[Link](“Simon”,
“Room 1234”, “x200”, 10);
[Link](1, c);
[Link](1, c);
[Link](“ClientAlreadyExists exception should be thrown if
client added twice”);
}

[TestMethod]
public void GetClient_TestGettingUnknownClient_ShouldGenerateException()
{
try
{
[Link](1);
[Link](“UnknownClient exception should be thrown if
client does not exist”);

Download free ebooks at [Link]

245
Object Oriented Programming using C# Case Study

}
catch([Link])
{
}
}

[TestMethod]
public void GetClient_TestGettingClient_ShouldNotGenerateException()
{
[Link] c = new
[Link](“Simon”,
“Room 1234”, “x200”, 10);
[Link] c2 = null;
try
{
[Link](1, c);
c2=[Link](1);
}
catch([Link])
{
[Link](“UnknownClient exception should not be thrown if
client exists”);
}
}

[TestMethod]
public void GetClient_TestGettingClient_AttributesShouldNotChange()
{
[Link] c = new
[Link](“Simon”,
“Room 1234”, “x200”, 10);
[Link] c2 = null;
try
{
[Link](1, c);
c2 = [Link](1);
[Link]([Link],10,”Value of returned credit not as
expected”);
}
catch ([Link])
{
}
}

[TestMethod]
public void GetClient_TestDeleteUnknownClient_ShouldGenerateException()
{
try
{
[Link](1);
[Link](“UnknownClient exception should be thrown if
client does not exist”);
}
Catch ([Link])
{
}
}

The tests above show numerous tests with an empty client book. They demonstrate that clients can be added, but not
twice. They also demonstrate that clients can be deleted and that exceptions are generated appropriately.

Download free ebooks at [Link]

246
Object Oriented Programming using C# Case Study

The figure below shows the results from running the tests….

By creating automated test fixtures to test all classes and all methods we can run these tests every time the system is
adapted to meet the clients changing needs.

11.13 Generating the Documentation


Documentation is essential and can be generated automatically (as described in Chapter 8 - C# Development Tools)
assuming appropriate comments have been placed in the code.

XML comments have been placed in the code to describe all classes, all constructors and all methods. All parameters,
return values and exception thrown have also been described.

Download free ebooks at [Link]

247
Object Oriented Programming using C# Case Study

Three of the comments taken from the Client class are shown below :-

/// <summary>
/// Manages a collection (sorted dictionary) of clients where each
/// client has an ID number (int).
/// </summary>
/// <remarks>Author Simon Kendal
/// Version 1.0 (5th May 2011)</remarks>
public class ClientBook
{
private SortedDictionary<int, Client> clients;

/// <summary>
/// Gets the clients.
/// </summary>
public SortedDictionary<int, Client> Clients
{
// ... lines missing ...

/// <summary>
/// Initializes a new empty instance of the <see
cref=”ClientBook”/> class.
/// </summary>
public ClientBook()
{
// ... lines missing ...
}

/// <summary>
/// Initializes a new instance of the <see cref=”ClientBook”/>
class and instantiates this to the disctionary passed.
/// </summary>
/// <param name=”clients”>A disctionary of Client ID, Client
objects.</param>
public ClientBook(SortedDictionary<int, Client> clients)
{
// ... code omitted ...
}

/// <summary>
/// Adds a client to the client book
/// </summary>
/// <param name=”clientID”>The client ID.</param>
/// <param name=”newClient”>The new client.</param>
/// <exception cref=”ClientAlreadyExistsException”> Throws
exception if a client with ClientID already exists</exception>
public void AddClient(int clientID, Client newClient)
{
// ... code omitted ...

Once XML comments have been placed throughout the code and exported, and comments have been added to the
Sandcastle Help File Builder tool to describe the namespaces then this tool can be used to generate a set of web pages to
describe the system…. virtually at the push of a button!

Download free ebooks at [Link]

248
Object Oriented Programming using C# Case Study

The following picture shows the main help page generated ‘[Link]’ documentation describing the Message Manager
System at its highest most general level i.e. the packages or namespaces within the system.

Start your career by joining the


Please click the advert

Nordea Graduate Programme

Check out our Graduate positions at


[Link]/career

Apply now in Sweden, Denmark or Finland!

[Link] Making it possible

Download free ebooks at [Link]

249
Object Oriented Programming using C# Case Study

The following picture shows part of the help documentation describing the UrgentMessage class:-

Download free ebooks at [Link]

250
Object Oriented Programming using C# Case Study

11.14 The Finished System


The following screen shots show the finished system.

Firstly the main interface window – this is very similar to the design. The only change was one extra button that was
added to allow a message to be designated as an urgent message.

The next two images show the pop up dialogues that appear when the ‘Find Client’ button is pressed.

Firstly asking for a client ID….

Download free ebooks at [Link]

251
Object Oriented Programming using C# Case Study

Secondly displaying the client details – assuming a client with this ID has been added.

The ‘Display Messages’ button shows each of the messages on the screen using the DummyBoard class. This is only crudely
simulating a real display board and makes no effort to scroll the messages or display them in any graphically interesting way.

Urgent messages look just like ordinary messages except ***’s are displayed before and after the message.

‘Purge Messages’ invokes the PurgeMessages() method. Mostly this does nothing visible but decrements the days remaining
for each message, decreases the client’s credits and deletes the messages if appropriate. Urgent messages are charged at
double the rate of ordinary messages. This can be tested by running Find Client before and after doing a daily purge – this
should show the clients credit decreasing. If messages exist with an unrecognised client ID and exception will be generated.
This exception will be caught by the PurgeMessages() method and an error message will be displayed on the screen.

Ultimately of course the idea would be to get the MessageManagerSystem to display the messages on a real display board.
This would involve 1) loading the DLL for the real display board 2) creating an object of the real display board in place
of the dummy display board 3) passing this object when calling the Display() method. i.e. only two lines of the entire
MessageManagerSystem would need to be changed!

11.15 Running the System


The complete, fully commented, source code for the Message Manager system, as described in this chapter, is available
with this textbook as zipped file. To view or run the Message Manager system :-

• Install Microsoft Visual Studio 2010 ([Link]


The C# express edition is free and will be perfectly adequate but will not allow you to run the unit tests.

• Download and unzip the file ‘OOP Using C#’… available with this book.

• Load the [Link] file into Visual Studio, view the code and run within Visual Studio.

Download free ebooks at [Link]

252
Object Oriented Programming using C# Case Study

In the zip file downloaded are all classes, methods and test cases discussed in this chapter. When viewing the Solution
Explorer in Visual Studio you will see all the packages, all of the classes and you should be able to view all of the code
with the associated comments (see below..)

You will not able to view to or run the test fixtures with Visual Studio express. Partly to overcome this we have shown
many of the test cases in this chapter.

Also inside this zip file is the automated documentation generated by the Sandcastle tool. To view the documentation go
to the ‘Documentation’ folder and double click on the [Link] page. This should load the documentation into your
web browser software.

If you install Sandcastle Help File Builder (available for free from [Link] you will be able to load the
file [Link] available as part of the Message Manager system download. You will then be able to
see that the comments for the namespaces have been added to the project properties and if you adjust the output path to
an appropriate path for yourself you will be able to rerun this software and see the documentation generated for yourself.

Download free ebooks at [Link]

253
Object Oriented Programming using C# Case Study

11.6 Conclusions
The fundamental principles of the Object Orientated development paradigm are
• abstraction
• encapsulation
• generalization/specialization (inheritance)
• polymorphism

These principles are ubiquitous throughout the C# language and the .NET APIs as well as providing a framework for our
own software development projects.

A well-established range of tools and reference support is available for OO development in C#, some of it allied to modern
‘agile’ development approaches.

Throughout this chapter you will hopefully have seen how Object Orientation supports the programmer by :-

• using abstraction and encapsulation to enables us to focus on and program different parts of a complex
system without worrying about ‘the whole’.

• using inheritance to ‘factor out’ common code

• using polymorphism to make programs easier to change

• using automatic tools to help document and test large software projects.

These principles have been exemplified here using C# but the same principles and benefits apply to all OO programming
languages and the facilities demonstrated here are available in many modern IDE’s.

Through reading this book, and doing the small exercises, you will hopefully have gained some understanding of these
principles.

If you want a further explanation of the C# language the following book is highly recommended…

Pro C# 2010 and the .NET 4 Platform by Andrew Troelsen

Finally I hope you have found this book helpful and I wish you all the best for the future.

Download free ebooks at [Link]

254

You might also like