Typemock Sponsors See# Party 2010 (#ssp2010)
Location: Kreuzlingen, Switzerland
The premiere See# Party in Kreuzlingen, Switzerland (on the shore of Lake Constance) gets underway tomorrow, offering a full-day of education with 16 speakers/sessions, and Typemock is proud to be a sponsor.
We caught up with See# Party organizer, Juergen Gutsch, to discuss his journey from ASP developer to conference organizer, organizational challenges, and open-source side projects.
Juergen’s official bio:
Juergen Gutsch works at the ASS.TEC Inc. as a software developer, team leader and leader of .NET development. Apart from his family and job, Juergen runs his own .NET User group ".NET-Stammtisch Konstanz-Kreuzlingen" and blogs about "ASP.NET and more..." at ASP.NET Zone.
TM: First, congrats on the conference. Tell us about your journey from ASP developer to event organizer.
Juergen: Right, I started out as a classic ASP developer and heavily used the community content at aspforum.de (now ASP.NET Zone). Over time, in addition to using, I started helping other novices and soon began doing community work. Later, because I contributed so frequently, I was asked to be a moderator on aspforum.de. When aspforum.de was renamed ASP.NET Zone, I began blogging about ASP.NET.
Blogging was not enough for a community-addicted geek like me and, because there was no .NET User Group within two hours of Konstanz, I unsuccessfully tried to start .NET User Groups in Konstanz (Germany) and Kreuzlingen (Switzerland)—due to lack of interest.
A year later, with a lot of help from Swiss ASP.NET MVP Peter Bucher, we successfully founded .NET- Stammtisch Konstanz-Kreuzlingen, the first .NET User Group to span the borders of Germany and Switzerland.
While leading the NUG and visiting different conferences I had the idea to organize a small conference. At first it only was an idea, but soon other User Group members had the same idea and asked me to organize a conference for .NET developers in Germany, Switzerland and Austria—giving birth to See# Party.
TM: Were there any special challenges to organizing See# Party?
Juergen: The first and biggest challenge was the time. From conception to the day of the event—we organized everything in only four months(!!). The second challenge was to convince potential sponsors that our premiere event would be successful. We also tried very hard to include as many different speaking topics as possible—to appeal to as many .NET developers as possible. Next year will be easier. :)
TM: What do See# Party attendees have to look forward to at the event?
Juergen: Attendees will get a full day of interesting sessions about developing with .NET technologies from a number of great speakers including Stefan Lieser, Laurent Bougnion, Golo Roden, Rainer Stropek, Thomas Schissler, Roland Weigelt and many more.
In addition, there will be plenty of networking time and even lunch sessions.
TM: Any interesting side projects to promote?
Juergen: I’m supporting the open source Inversion-of-Control container, LightCore, which is developed by the ASP.NET MVP Peter Bucher. If you want to have a lightweight and very fast IoC container, then take a look at lightcore.ch
Typemock is proud to sponsor See# Party and will be raffling two Typemock Isolator licenses at the event plus a special offer for all its attendees. Be sure to attend Stefan Lieser’s session on Typemock Isolator and Brownfield Projects for an additional giveaway.
Typemock Isolator makes unit testing easy. It’s easy to learn, easy to use, and includes powerful features that make it a must-have tool for .NET developers. Isolator supports all .NET technologies including, WCF, Silverlight, ASP.NET, WPF and SharePoint.
If you would like to know more about how Typemock Isolator makes unit testing so easy, or if you have an event you would like us to sponsor please email me at britt [at] typemock [dot] com and let's chat about it.
-Britt King
Debugging the Undebuggable
I bumped up against an interesting problem today. I was trying to write a unit test for our CRM code (I’ll write about my endeavor in a another post). 
Anyway, I was trying to test a method (a WebMethod, actually) that was inside a class, which was inside an asmx file. Strangely enough, I never did that before, and was ready to conquer another framework with Isolator.
I was just looking to add a reference to the site from my test project. But that did not work – apparently you can’t add a reference to a site project. The next surprise (to me. Those doing it everyday, probably have figured this out eons ago) is that when you build a site, you don’t get a ready-made bin directory where I expected it would be.
It did not dissuade me. I took my trusty Reflector with me and found out that there is a bin directory under the PrecompiledWeb folder, and an assembly called App_Code.dll contains my class. I added the reference in my test project directly to this assembly. Then I went on to write a test.
Expectedly, my test failed a couple of times (I was using the Act-Assert-Arrange method for writing tests). I looked at the code, added some Isolate.Fake.StaticMethods<>, and then when it insisted to fail, I decided to debug. Immediately I figured that I couldn’t step into the class. I looked for PDB files, but couldn’t find them (probably looking in the wrong places). I tried putting a Debugger.Break command in my class, but that did not work either (probably due to some caching or something. As you’ve figured out by now, I was not really in a research mode).
So how can I debug this class, without breaking a sweat?
I took the class file (myclass.asmx.cs) and added a link to it in my test project. Presto. Now the class-under-test is in the test project. I added a couple of missing references, and the class was now debug-able. The test was completed a few minutes later.
We always talk about easy unit testing. And it is easy when you know how, including when you have this kind of ammo in your bag of tricks. When you learn a trick – teach others - they deserve to know as well!
What’s the coolest way that you found to go around a testing problem?
Isolator++ Beta News
The latest beta of Isolator++ is up on the site. Here are a couple of the features that you now can do:
- Support for VS2010. Apart from the support for the IDE, the examples also contain a solution for VS2010, so you can look at what’s new there.
- Faking global functions. If you look at the example on the Isolator++ product page, you’ll see how fopen is no longer a problem for testing.
- Faking private methods. Nuff said.
- Future objects : those pesky things you create with "new" in the code-under-test, can now be faked.
- Live objects: Let's not forget objects you create in your test, but are not fake, and you just want to change their method's behavior.
And of course there are fixes of bugs and more features creeping in, as much as we can. Check out the beta and let us know what you think about it.
How to fake C++ objects with Isolator++ (Beta)
It seems like everything in the C++ world is harder – you have two files per class, no garbage collection and you need to know your pointer tricks to get things done. It would have been only natural that unit tests would flourish in such a world that a project could live or die by it’s memory leaks. Unfortunately this is not the case, perhaps one of the reasons that the practice of unit testing code is not that common is that like everything else – writing unit test in C++ is not that easy, at least not easy as it is on the managed world.
The good news is that it got easier with the new beta of Isolator++ that brings the proven methodologies and expertise from the .Net Isolator to C++ land.
In this post I’ll show how to fake classes in order to write simple, maintainable unit tests.
The problem at handOur story begins with a need to create a BusinessObject that can be persisted (i.e. saved to database). We want to make sure that after a newly created object is saved ,its dirty flag is set to false.
Here is my simple BusinessObject implementation:
Header (.h)
#pragma once
class DAL;
class BusinessObject
{
int m_id;
bool m_isDirty;
DAL* m_dataAccess;
public:
BusinessObject(int id, DAL* dataAccess);
~BusinessObject(void);
bool IsDirty()const{return m_isDirty;}
void Save();
};
Implementation (.cpp)
#include "StdAfx.h"
#include "BusinessObject.h"
#include "DAL.h"
BusinessObject::BusinessObject(int id, DAL* dataAccess): m_id(id), m_dataAccess(dataAccess), m_isDirty(true)
{
}
BusinessObject::~BusinessObject(void)
{
}
void BusinessObject::Save()
{
m_dataAccess->Save(*this);
m_isDirty = false;
}
As you can see creating a new object sets the IsDirty flag to true and calling Save sets it to false – per our requirements.
Testing the BusinessObjectI’ve used google’s testing framework to write the unit test and it’s as simple as you’d expect it to be:
#include "stdafx.h"
#include <gtest\gtest.h>
#include "BusinessObject.h"
#include "DAL.h"
class BusinessObjectTests : public ::testing::Test
{
};
TEST_F(BusinessObjectTests, IsDirtySetToFalseOnSave)
{
DAL* dataAccess = new DAL();
BusinessObject* bo = new BusinessObject(1, dataAccess);
bo->Save();
ASSERT_FALSE(bo->IsDirty());
}
I find it quite readable – even if you are not familiar with GTest – it’s a single test that does the following:
- Create a new data access layer
- Create a new BusinessObject
- Call Save
- Assert that IsDirty is set to false
For more information on writing tests using GTest – have a look at the documentation or Isolator++ getting started page.
Unfortunately running the test fails – miserably:
As you might have already guessed – the reason for this “crash” comes from the bowels of the DAL object. Because we do not have an actual database – in fact I haven’t even implemented it yet.
But I won’t let such trivialities as a missing database stop me – I want to test the logic of the object, not the way it’s saved. This is where Isolator++ comes in.
Isolating the business logicWhat I need for the test to pass is to create a “fake” data access object. It may look like a regular object, but every method that gets called on it, doesn’t do anything.
Creating a fake object with Isolator++ is simple: just link to the IsolatorCore library and add and include Isolator.h and you’re set to go.
This is how the updated test looks like:
#include "stdafx.h"
#include <gtest\gtest.h>
#include <isolator.h>
#include "BusinessObject.h"
#include "DAL.h"
class BusinessObjectTests : public ::testing::Test
{
};
TEST_F(BusinessObjectTests, IsDirtySetToFalseOnSave)
{
DAL* dataAccess = FAKE(DAL);
BusinessObject* bo = new BusinessObject(1, dataAccess);
bo->Save();
ASSERT_FALSE(bo->IsDirty());
}
Notice the FAKE macro that is used to create the DAL object.
And now the test should pass – which we can verify by running it:
That’s it. The very basics of Isolator++.
More information on faking objects can be found on Isolator++ online user guide.
Happy coding
How to verify a method call on a dependency
Guest post by Lior Friedman.
Interaction testing is a common type of unit testing. In this type of tests, one checks that a specific unit “interacts” with another way according to an agreed protocol, usually this protocol is embodied in the used class API. Its in interaction tests that mocking framework becomes real handy.
Let’s do an example.
I have a system, which tracks my schedule. It publishes a certain API that enable to ask me to do things. However,internally it works asynchronously. When it receives a request, it verifies that it can handle the request. If this condition is met, it issues a request on a message queue in order to switch the execution content (and handle the details with the request).
In order to keep the example simple I’ll ignore the need to return an answer from the requested execution.
Here’s a simple example of such an API method:
public bool PickKidsFromSchool(DateTime onDate)
{
if (TooFarInThFuture(onDate))
{
return false;
}
if (!Free(onDate)
&& CantMoveAppointments(onDate) )
{
return false;
}
var request = new PickKidsRequest(onDate);
_RequestQueue.Enqueue(request);
return true;
}
And here’s the logic in charge of the actual handling of the message:
public void HandleRequest(MySchedule Scheduler)
{
Scheduler.FreeTime(
SCHOOL_END_TIME,
MySchedule.Evening);
Appointment appointment =
new Appointment("Pick kids");
Scheduler.SetAppointment(
appointment,
_RequestDate,
SCHOOL_END_TIME);
}
There are several ways to tackle testing of such a component. My preferred way is to split the problem into two main parts (and a smaller hidden one) and test each part separately: The first part is to test the handling logic (HandleRequest) , i.e. after the message was taken from the queue. The second part is to test API method (PickKidsFromSchool), making sure it does the proper verification, and at the end issue “enqueue” the proper message on the queue. We’re not going to talk about those today.
The “hidden” part is to verify that the queuing mechanism itself is working properly. Specifically, we need to make sure we’re able to pass a message to and from the queue to the appropriate handler.
Here’s how I use Isolator in order to verify specific calls, and how it allows me to test the second part.
Here is the test:
[TestMethod()]
[Isolated]
public void PickKids_HasTime_EnqueRequest()
{
var fakeQueue =
Isolate.Fake.Instance<Queue<Requests>>();
DateTime onDate = new DateTime(2010, 8, 10);
var target = new MySchedule(fakeQueue);
target.PickKidsFromSchool(onDate);
var expectedRequest =
new PickKidsRequest(onDate);
Isolate.Verify.WasCalledWithExactArguments
(() => fakeQueue.Enqueue(expectedRequest));
}
The interesting line is the last line of the test:
Isolate.Verify.WasCalledWithExactArguments
(() => fakeQueue.Enqueue(expectedRequest));
This statement verifies that a message was sent to the queue, and also verifies that the sent message matches the expected message supplied. The test fails if neither of these conditions are met.
Similarly I can use the following statement to verify that a message was not queued, which is necessary to test cases that reject the request.
Isolate.Verify.WasNotCalled
(() => fakeQueue.Enqueue(null));
In conclusion: because our code interacts with other pieces, we need to know it calls them, and does so correctly. With Verify it’s easy to set the pass/fail criterion for interaction, and make sure the correct call on the dependency was made.
Typemock Summer Sale
There are many things that make a summer: sea, sun, cocktails. Everything you see in that logo up there.
But this summer, we give you something way cooler (pun intended). The Typemock Summer Sale 2010 starts today. When you purchase Isolator, you can choose between a 50% off the purchase, or get the entire suite of Typemock products.
Either way – it’s a win for you. We always talk about easy unit testing. It doesn’t get easier than this.
Visit our Summer Sale page now!
Typemock Sponsors #devLink2010, August 5 - 7th
Location: Nashville, Tennessee – USA
The devLink Technical Conference kicks-off tomorrow, offering 3 days of education and over 150 sessions on current and emerging technologies, and Typemock is proud to be a sponsor.
We caught up with devLink Founder and Chairman, John Kellar, to discuss the history of the conference, the development culture in Nashville, organizational challenges, WPF side projects and even the caped crusader himself.
John’s official bio:
John Kellar is the Director of Software Development and Consulting for Useful Devices Inc. (www.usefuldevices.com). In addition to being Founder and Chairman of the devLink Technical Conference (www.devlink.net), he is a member of the Nashville .NET User Group (www.nashdotnet.org) Board of Directors and a speaker at technical events. John has worked on applications in several markets including healthcare, government, financial services and manufacturing. You can view his blog at http://www.johnkellar.com.
TM: John, tell us about your personal journey from technology enthusiast to professional developer to event organizer.
JK: Well if you want to way back, I wrote my first program back in the 80s as a kid on a old Texas Instruments system, saving it to a cassette tape.
I got my real professional training when I was in the Navy and loved it so much I decided to pursue it in the civilian world. After several years developing I wanted to keep my skills up to date and heard about a fellow by the name of Mike Wiley looking to start a User Group in Little Rock (Arkansas).
Long story short, we ended up working together with some other folks and created the Little Rock .NET User Group. I love learning and started speaking some on topics I was familiar with.
To celebrate our first year we put on an all day event with a single track called Tech Expo and had tremendous success. The next year we did it again and had an even greater turnout.
When I moved to Nashville I got involved with the User Group there as well, but wanted to recreate the mini conference similar to what we did in Little Rock. So I worked with a guy named Tommy Norman who was already plugged into the Nashville community and created the Devlink Technical Conference. From there it has grown into a large regional conference with hundreds of industry professionals attending every year.
TM: what's the development culture like in the Nashville area?
JK: Nashville is a unique area in that it is very heavy in the Microsoft .NET arena. I'm not sure why certain cities tend to be stronger in a specific technology than others, but Nashville it definitely a big Microsoft town. Nashville has a pretty good mix of development philosophies and an active community full of developers looking to expand their knowledge.
TM: what challenges did you face while organizing the event?
JK: There are so many it is hard to identify just a few. Running a conference is not unlike building software, you understand the processes that need to take place and figure out how to streamline them. Sometimes you have to make the hard decisions and cut things that you really want to do. Every year we think about how we can make things better and add new things that we really want to do. As we are able, through sponsorship dollars, we add more and more. Essentially we work from the fund it first mentality so we (hopefully) never promise something that we cannot deliver.
TM: which topics are you looking forward to learning more about at the event?
JK: Well, I don't get to sit through many sessions because it is time consuming running an event. By the second day the core folks are all running on adrenaline, so to sit in a session is tough. I have a number of sessions that I would love to see and if I can find a way, I will squeeze into them the best I can.
TM: which technologies interest you most and why?
JK: Personally, I think WPF and Silverlight primarily because they are going to take the User Interface to the next level. You can do so much more than was possible with older technologies. I also have an interest in digging more into iPhone and Android, but there are only so many hours in the day.
TM: any interesting side projects to promote?
JK: I have been working on some game development with WPF which has been great fun. Some of that work was leveraging the 3D capabilities which has been an amazing learning experience for me.
TM: last question: who’s your favorite superhero?
JK: Batman, because he has the best gadgets.
TM: LOL, yes his gadgets rock!
Typemock is proud to sponsor devLink 2010 and will be raffling two Typemock Isolator licenses at the event plus a special offer for all its attendees.
Typemock Isolator makes unit testing easy. It’s easy to learn, easy to use, and includes powerful features that make it a must-have tool for .NET developers. Isolator supports all .NET technologies including, WCF, Silverlight, ASP.NET, WPF and SharePoint.
If you would like to know more about how Typemock Isolator makes unit testing so easy, or if you have an event you would like us to sponsor please email me at britt [at] typemock [dot] com and let's chat about it.
-Britt King
Typemock Supports #SharePoint Saturday NY #SPSNY
SharePoint Saturday New York kicks-off tomorrow in the big apple. SharePoint architects, developers, and other professionals that work with Microsoft Office SharePoint Server will gather at the Microsoft Manhattan Office for a full day of sessions from respected SharePoint professionals & MVPs, covering a wide variety of SharePoint-orientated topics.
Becky Isserman, Jason Gallicchio and the other organizers have put together a diverse lineup of speakers and sessions that SharePoint developers are sure to love. Trust me, the love is apparent. At last count, the event is sold out with more than 70 developers on the wait list!
Typemock is a proud sponsor of SharePoint Saturday New York and we’ll be raffling two Typemock Isolator for SharePoint licenses at the event. Don’t miss our special offer for all SharePoint Saturday NY attendees.
Typemock Isolator for SharePoint makes it easy to test your webparts or any other SharePoint components (including support for SharePoint 2010).
As always, if you would like to know more about how Typemock Isolator makes unit testing SharePoint so easy, or if you have an event you would like us to sponsor please email me at britt [at] typemock [dot] com and let's chat about it.
-Britt
Isolator++ (for C++ devs) Now in Open Beta
Isolator++ has grown up and is moving to an open beta!
Isolator++ was in a closed beta for a few weeks now. With the feedback we got, it’s now bett
er, faster, stronger. And it’s now ready for a public beta!
We’re still adding features to the product, but now everyone can take it for a ride. Just a few things Isolator++ can do today:
- Fake instances of concrete classes
- Fake instance and static method calls
- Change behavior of methods, including:
- Returning values
- Throwing exceptions
- Ignoring void methods
- Running custom code (DoInstead anyone?)
- Asserting method calls
Think that’s enough? Here’s what coming: Global call support, non-public method support, future objects – and we still have lots of time before we launch.
Think you’re up to the task? Know someone who does? Register and download Isolator++ now!
How do you test asynchronous code? Part I
This is the first part of Stefan Lieser’s article appearing in DotNetPro. Stefan was gener
ous to translate the article and post it here. (Read part II)
Stefan Lieser works as a consultant, trainer and author. He is interested in agile methods and looking for improvement every day. Together with Ralf Westphal he started the Clean Code Developer initiative (see http://clean-code-developer.de) which gains lots of interest in both the .NET
and Java software developer community. Furthermore he was one of the organizers of the .NET Open Space in Leipzig, Germany.
How do you test asynchronous code? Part I
Most developers know that external resources should be accessed asynchronously over the network. Yet some frameworks like Silverlight don’t support synchronous access. This article answers the question of how to test asynchronous methods that use internal or sealed classes from the .NET Framework.
The .NET Framework offers asynchronous access for longer running resource accesses. For example, the class WebClient from the System.Net namespace has methods to load data from the web in the background. In principle this is a good thing because you need those asynchronous methods if you don’t want your UI freezing while loading the data. If the download is started synchronous the UI would have to wait for the incoming data. Splitting the download and the UI into two parallel running threads is a must to get a reactive user interface.
Typical code snippets for asynchronous access look like this:
public void LoadArticles() {
var webClient = new WebClient();
webClient.DownloadDataCompleted += OnCompleted;
var url = new Uri("http://example.de/articles");
webClient.DownloadDataAsync(url);
}
private static void OnCompleted(object sender, DownloadDataCompletedEventArgs e) {
byte[] articlesXml = e.Result;
// do something with the XML
}.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
It’s necessary to know that the method call to DownloadDataAsync returns right after the call. The download operation is then moved to the background into its own thread. After the download is completed (or an error occurs) the event DownloadDataCompleted will be raised, so you need to bind a method to this event that handles the incoming data.
webClient.DownloadDataCompleted += OnCompleted;
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
The data that was loaded in the background is handed to this method by the event argument. It contains a field Result that contains the data as a byte array. If an error occurs this is signaled in the field Error. It will then contain an Exception. Check for an error before accessing the data.
It’s always a good idea to encapsulate resource accesses behind a repository. This way you can define an interface for the repository and it’s easy to mock it away in unit tests. But if you implement a repository for the shown LoadArticles method make sure that your repository is asynchronous too. Otherwise you are back in the synchronous world - needing to use the same method pattern plus an event in the repository interface:
public interface IArticleRepository
{
void LoadArticles();
event Action<IEnumerable<Article>> OnArticlesLoaded;
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
The pattern shown here for the WebClient class is used in the .NET Framework on many other places. So how should one use this infrastructure so that it can be tested automatically? There are two challenges:
• How to test usages of WebClient without really starting a download from a server
• What to do with the parallel execution of the test and the WebClient call
The answer to the first question is easy: in order to use a dummy resource instead of the real one we need to mock the access to WebClient. The second problem is more difficult because the parallel execution isn’t the root cause of the problem. But let’s first focus on the first problem, the mocking of a WebClient.
A mock for WebClient
In the example code the WebClient instance is created inside the LoadArticles method by using new. This is considered by some as the normal way of instantiating an object. The problem with the example is that the usage of the class WebClient is now hardwired inside of the method. We need to inject an instance to be able to use a mock instead of the real WebClient class. Then we can inject a special testing mock while unit testing our ArticleRepository. We can accomplish this by adding an additional constructor as shown in the following snippet:
public ArticleRepository()
:this(new WebClient()) {
}
internal ArticleRepository(WebClient webClient) {
this.webClient = webClient;
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Only the default constructor is made public. The constructor that is used for testing purposes only is made internal. Clients of the class need not be changed because they still use the parameterless default constructor. In order to use the internal constructor in our unit test project (you separate tests from implementation, don't you?) we need to add an additional attribute to the implementation project:
[assembly: InternalsVisibleTo("myAssembly.Tests")].csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
With this attribute in place our testing assembly can use the internals from the implementation assembly. Clients of the implementation assembly only have access to the public interface.
Back to injecting the WebClient: you may have noticed that the semantics of the class were changed slightly by injecting one WebClient instance in the internal constructor. In the former version we instantiated a new WebClient object in each call to the LoadArticles method. To get back to these semantics we can use a little lambda expression:
public ArticleRepository()
:this(() => new WebClient()) {
}
internal ArticleRepository(Func<WebClient> webClientFactory) {
this.webClientFactory = webClientFactory;
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Now we don’t inject a WebClient instance but, instead, a function that yields a WebClient instance. The LoadArticles method now has to use this function instead of new to get a fresh WebClient object:
var webClient = webClientFactory();
This factory method gives us the flexibility we need in unit testing the code.
This is the end of part I. Tune in next week for part II.
How do you test asynchronous code? Part II
This is the second part of Stefan Lieser’s article appearing in DotNetPro. Stefan was gener
ous to translate the article and post it here. (Read the first part)
Stefan Lieser works as a consultant, trainer and author. He is interested in agile methods and looking for improvement every day. Together with Ralf Westphal he started the Clean Code Developer initiative (see http://clean-code-developer.de) which gains lots of interest in both the .NET
and Java software developer community. Furthermore he was one of the organizers of the .NET Open Space in Leipzig, Germany.
How do you test asynchronous code? Part II
It‘s all faked
We can now use the additional constructor to inject a mocked WebClient instance so we don’t start a real download in the automated tests. To be able to inject a mock in tests and “the real thing” in production we need a common interface for both. Unfortunately, Microsoft decided that WebClient would not implement any interface. It only inherits from Component which is of no use in this context. I see two ways out of this dilemma: the first is to define our own interface. That means implementing a wrapper class around WebClient that implements our interface and uses WebClient internally to do its job. Writing such wrappers is not only dull but also more difficult: class DownloadDataCompletedEventArgs has only internal constructors so we can’t use it in our wrapper. Going the wrapper route means not only wrapping WebClient but implementing our own EventArgs class. What those wrappers may look like is shown by the following code snippets:
public interface IWebClient
{
event EventHandler<DownloadDataCompletedEventArgsWrapper> DownloadDataCompleted;
void DownloadDataAsync(Uri address);
}
public class WebClientWrapper : IWebClient
{
private readonly WebClient webClient = new WebClient();
public WebClientWrapper() {
webClient.DownloadDataCompleted += ProcessDownloadDataCompleted;
}
private void ProcessDownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) {
DownloadDataCompleted(sender, new DownloadDataCompletedEventArgsWrapper(e));
}
public event EventHandler<DownloadDataCompletedEventArgsWrapper> DownloadDataCompleted = delegate { };
public void DownloadDataAsync(Uri address) {
webClient.DownloadDataAsync(address);
}
}
The real WebClient class is used inside the wrapper to do the work. The methods from the wrapper refer to the WebClient instance to do their work. If you don’t want to write those wrappers you will need a powerful testing tool.
Mocking with the Profiler API
Instead of writing wrappers for infrastructure classes from the .NET Framework we can use powerful technologies like the Profiler API to be able to mock the objects. By using the Profiler API one can intercept nearly every call. That’s what the popular Typemock Isolator uses internally.
I’m still a fan of injecting dependencies as mentioned above with an internal constructor to make the tests more expressive. Typemock Isolator, however, can intercept even the call to new inside of the method. Using Typemock Isolator the automated test looks like this:
[TestFixture]
public class ArticleRepositoryTests
{
private ArticleRepository sut;
private WebClient webClient;
private IArticleReader articleReader;
[SetUp]
public void Setup() {
webClient = Isolate.Fake.Instance<WebClient>;
Isolate.WhenCalled(() => webClient.DownloadDataCompleted += null).CallOriginal();
articleReader = Isolate.Fake.Instance<IArticleReader>();
sut = new ArticleRepository(() => webClient, articleReader);
}
[Test, Isolated]
public void WebClient_Data_is_handled_by_Reader() {
var e = Isolate.Fake.Instance<DownloadDataCompletedEventArgs>();
var count = 0;
sut.OnArticleLoaded += delegate { count++; };
sut.LoadArticles();
Isolate.Invoke.Event(() => webClient.DownloadDataCompleted += null, null, e);
Assert.That(count, Is.EqualTo(1));
}
}
In the example we created a WebClient instance using the following snippet:
webClient = Isolate.Fake.Instance<WebClient>;
Because we used Isolator to instantiate the object we were able to modify its behavior in the test. Isolator intercepted the call to DownloadDataAsync. The download didn't really start and we isolated our repository from the real resource.
In order to give the repository some test data we had to invoke the DownloadDataCompleted event. And doing this meant that we needed an instance of the event argument. As mentioned above this had an internal constructor but with Isolator to the rescue we solved this with the following snippet:
var e = Isolate.Fake.Instance<DownloadDataCompletedEventArgs>();
After creating the event argument we told Isolator to raise the event:
Isolate.Invoke.Event(() => webClient.DownloadDataCompleted += null, null, e);
In the end this test shows that the data that is transmitted by the WebClient to our repository is received by the object that handles the data.
What about asynchronicity?
But now back to the problem of testing the asynchronous call. As shown in the code example the ArticleRepository uses WebClient to download the XML data and creates article objects from that data. The repository itself should not map from XML to article objects. If it did, the tests would be much more difficult because the data would have to go through the WebClient mock.
In order to separate the mapping concern we could inject another object into the repository. The responsibility of the repository would then be to download the data by using the WebClient and hand it over to a mapper to create article objects from it. So let's create an interface for that:
public interface IArticleReader
{
IEnumerable<Article> Read(byte[] articleXml);
}
The IArticleReader maps from a byte-array containing the XML to an enumerable of articles. That’s pretty easy to test.
The only thing we have to test for the repository is if it hands the downloaded data to the IArticleReader object:
[Test, Isolated]
public void WebClient_Data_is_handed_to_article_reader() {
var e = Isolate.Fake.Instance<DownloadDataCompletedEventArgs>();
var downloadedData = new byte[0];
Isolate.WhenCalled(() => e.Result).WillReturn(downloadedData);
sut.LoadArticles();
Isolate.Invoke.Event(() => webClient.DownloadDataCompleted += null, null, e);
Isolate.Verify.WasCalledWithExactArguments(() => articleReader.Read(downloadedData));
}
Where have the async problems gone? They have disappeared because we separated the concerns of the repository. We now only need an integration test that verifies we can really download the data from a real server and deliver the correct article objects. And of course that integration test needs to handle the asynchronous method call
The problem with the integration test is that after calling LoadArticles the method immediately returns, forcing us to wait for the result. But how long should we wait, ten seconds? That may be enough on a developer machine but not on the build server. Waiting even longer means slowing down the tests so using Thread.Sleep is not a good idea.
I recommend using an EventWaitHandle which makes it possible to wait for the event or a timeout. The test looks like this:
[Test]
public void Articles_get_loaded() {
var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
var count = 0;
sut.OnArticleLoaded += delegate(IEnumerable<Article> articles) {
count++;
Assert.That(articles, Is.Not.Null);
waitHandle.Set();
};
sut.LoadArticles();
var wasSignalled = waitHandle.WaitOne(5000);
Assert.That(wasSignalled, Is.True, "A timeout occurred");
Assert.That(count, Is.EqualTo(1));
}
Conclusion
Testing is easy if the basic principles for inner software quality are followed. In this example the Separation of Concerns leads to code that is easy to test. Of course, principles need to be followed in the context of a value system. If the only value were correctness than writing the wrapper classes would not be a problem. There is, however, the value of production efficiency. It’s more efficient to use tools like Typemock Isolator to overcome technical limitations. You may decide not to inject every dependency and that's fine, as long as it’s good for efficiency and does no harm to correctness and evolvability.
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
SharePoint Down Under
“Don’t worry about the world coming to an end today, it’s already tomorrow in Australia.” – Charles M. Schulz
The month of August is just around the corner, can you believe it? To us in the northern hemisphere that means the dog-days of summer are upon us. Hordes of Europeans are packing up their caravans and making the annual migration to the beach while those in North America busy themselves with backyard BBQs and their own vacation plans.
If you’re part of the SharePoint community in Australia, however, the month of August marks the beginning of winter’s end and the kickoff of 3-months worth of SharePoint Saturday events, nationwide.
We recently caught up with Elaine Van Bergen, SharePoint MVP and community leader from the Melbourne area, to talk a bit about her journey from SharePoint novice to specialist extraordinaire, the development culture in Melbourne, her technology interests and some of the development challenges she’s faced recently.
TM: G’day, Elaine. Tell us what you’re up to at the moment.
EVB: I’m an Architect at OBS in Melbourne and a Virtual Technology Solutions Professional for Microsoft Australia. I’m also a Microsoft Office System Special Interest Group (MOSSIG) board member.
TM: How long have you been using SharePoint?
EVB: I’ve been working extensively with SharePoint since the 2001 version and have been involved in all areas of projects including gathering requirements, assisting with governance, defining infrastructure and application architecture, solution development and training.
TM: Tell us about your journey from technology enthusiast to professional developer to community leader.
EVB: I jumped into .Net programming when it was in its beta phase, and also got involved with SharePoint very early on. In both cases there wasn’t a heap of public information around on various topics so attending local user groups was a great way to find out information such as best practices or how to solve particularly difficult problems. By attending I also met a lot of people with similar technology interests. Over the years I then started to present on various topics and eventually decided to help get involved in running MOSSIG
TM: What's the development culture like in the Melbourne area?
EVB: I think we have a great culture, plenty of active user groups and online communities with people sharing a lot of information !
TM: What development challenges have you faced recently?
EVB: With SharePoint development there is always a battle to ensure that code is developed in a best practices manner. There is still really low awareness on simple topics such as using design patters and creating a layered solution structure including unit testing.
TM: Something tells us you like SharePoint ;) , tell us why.
EVB: I’m passionate about SharePoint. It’s an incredibly powerful platform that offers a lot through configuration , you can then really ramp it up to the next level by coding on top of it. It means that a lot of the ‘framework’ type of pieces are taken care of by the platform so things like how to store a document, search and security don’t need to be built so you can concentrate on building requirements that are more unique to the customer.
TM: What are some things you're hoping to do with Isolator for SharePoint?
EVB: Help build more robust code by ramping up the amount of unit testing in projects that I work on.
TM: Any interesting side projects to promote?
EVB: SharePoint Saturday events coming up in Australia, I’m helping organize Melbourne but also hoping to get along to Sydney and Canberra.
SharePoint Saturday kicks-off August 7th in Sydney, followed by Canberra (September 18th) and Melbourne (October 30th).
Typemock is a proud sponsor of SharePoint Saturday in Australia. Typemock Isolator for SharePoint makes it easy to test your webparts or any other SharePoint components (including support for SharePoint 2010).
-Britt
Finding bugs? I’ve got customers for that!
I read about bug bounty in a couple of articles. This is a prize for people who find critical bugs in software, and the focus is about security. Both Google and Mozilla put a lot of focus about security, making the user feel secure. A noble cause indeed.
Do you see something wrong with this picture?
Let’s see where this logic leads us: We want people to feel secure using our products,so we would rather let other people (NOT US) find the most critical bugs. And guess what: It’s very cost effective. If those “elite” bugs cost me just $3K to find, do you know how much I’m saving in testing costs?
I’ve often said that when you test your code that makes you a responsible developer. That goes for organizations as well. Yeah, it might look neat and 1337 (I actually smiled when I saw what Google offers as a prize), but make no mistake: It’s just passing the buck.
So give me a break. You want to convince me your product is good? Test it yourself. Find the bugs before the next user gets her data exposed. Be responsible.
Free Unit Testing Webinar on LIDNUG with @Typemock
I want to quickly tell you about an upcoming live unit testing webinar, featuring Gil Zilberfeld from Typemock, that you may find valuable.
Here's the abstract:
Unit Testing in the Wild
You know that unit testing is good for you. But the calculator examples that you’ve read are not helpful in the real world. Gil Zilberfeld, Typemock’s Technology Evangelist, will talk about what you need in order to succeed, from the perspectives of developers and team leaders. We’ll see how Typemock tools assist with unit testing adoption, and show tips for starting on the right foot. Gil will show examples for unit testing problematic solutions in WCF, ASP.Net and SharePoint.
About the Presenter: Gil Zilberfeld has been developing software for over 15 years, and has vast experience in implementing development practices. Gil is the Technology Evangelist at Typemock, promoting unit testing and some incredibly cool tools. Gil brings his real-life experience, along with a bit of sarcasm, since these two are a match made in heaven. Follow Gil on twitter: @gil_zilberfeld and read his blog at http://www.gilzilberfeld.com
The live webinar is scheduled for Thursday, July 22nd from 11:00AM to 12:30PM PDT/PST (GMT-8) on LinkedIn .NET Users Group (LIDNUG). Are you familiar with LIDNUG? If not, I can tell you that Brian H. Madsen and the other organizers are doing a great job in attracting developers from around the world to join in discussion on .NET-related topics and live webinars. They recently passed the 38000 (!!) member mark and there doesn't appear to be any signs of slowing.
If you and other developers you know would like to attend the live webinar, simply go to the Events page here, click on Gil's presentation, RSVP and follow the login instructions.
Thanks, and contact us with any questions
Regards,
Typemock back to basics: Faking "Future" Instances
Guest post by Lior Friedman. This is a part of a series called “Back to basics” of unit testing.
One of the best things about the Isolator is that it can fake instances which are created inside the production code. This kind of faking is called "faking a future instance".
Lets see an example how this can be used. Here's my production code that I need to test:
public class Client
{
Server m_Server = null;
public Client(IPAddress addr)
{
m_Server = new Server();
m_Server.Connect(addr);
}
public int SendInfo(string message)
{
m_Server.Send(message);
string answer = m_Server.Recieve();
if (answer != "OK")
{
throw new ApplicationException
("Failed To Communicate");
}
return message.Length;
}
}
The method I want to test is SendInfo, and a simple test would be to make sure that when sending is successful, the actual number bytes sent is returned by it.
The tricky bit resides in the Constructor of the Client class . As you can see, the client creates his own server and connect to it based on the address given by the user.
Here's the test code:
[TestMethod()]
public void SendInfo_SuccesfulSend_SendsAllBytes()
{
//creating the fake
Server fakeServer = Isolate.Fake.Instance<Server>();
//setting behavior
Isolate.WhenCalled(() => fakeServer.Recieve()).
WillReturn("OK");
//When the next Server is created, swap it with fakeServer
Isolate.Swap.NextInstance<Server>().With(fakeServer);
var address = new IPAddress(
new byte[] {192,168,0,9}
);
string message = "Hello Server";
Client target = new Client(address);
int actual = target.SendInfo(message);
Assert.AreEqual(message.Length, actual);
}
Specifically important is this line:
//When the next Server is created, swap it with fakeServer
Isolate.Swap.NextInstance<Server>().With(fakeServer);
After I've created the fakeServer and set the desired behavior, this command tells Isolator to swap the next created instance with the fakeServer I've created. That is, the next time someone will will create an instance of the Server Class (as done in the client constructor), Instead of getting a real server he will get the fake instance I specified in the "With" segment.
By the way, in the “With” clause, I can supply a fake or a real object. Quite simple isn't it?
Test Lint Pro – Launch Sale
Test Lint Pro just launched, and we decided to have a special launch event. So until July 30th, we’re offering a double offer:
- You can get Test Lint Pro for the introductory price of 199!
- Or, with buying two licenses of Typemock Isolator you get a free license of Test Lint Pro!
Don’t forget – you can download the regular Test Lint for free.
We always talk about how Typemock makes unit testing easy. Having the tool work in combination is powerful stuff. For more information contact us sales at typemock dot com.
Typemock Isolator++
On April Fools we said we were leaving the .net world behind, and going where no isolation framework has gone before - C++ land. This was not completely false.
Today we’re announcing Isolator++, Typemock Isolator’s brother, intended for C++ developers. Isolator++ is now in a closed beta. If you want to take Isolator++ for a ride, join the beta program, or know someone who would be interested, contact me, gilz at typemock dot com.
In the meantime, you can read more about Isolator++ in our guide:
Isolator++ is intended for the C++ Windows developer. We’re adding features weekly, and I’ll keep you posted about new stuff, as they come in, and a new version is ready for download.
Video: Kent Beck on JUnit Max and Lean Startups
Typemock Sponsors #NWATechFest – July 8th
The first annual NWA TechFest will kick-off on Thursday, July 8th in Rogers, Arkansas and Typemock is happy to be a sponsor. Like all good technology events, NWA TechFest will focus on improving the day-to-day lives of professional developers through training/teaching sessions on Visual Studio 2010, Silverlight 4, SharePoint 2010 and other technologies.
David Walker and the other organizers have put together a diverse lineup of speakers and an event that includes 9 tracks and 45 sessions!
We will be raffling two Typemock Isolator licenses at the event plus a special offer for all its attendees.
As always, if you would like to know more about how Typemock Isolator makes unit testing so easy, or if you have an event you would like us to sponsor please email me at britt [at] typemock [dot] com and let's chat about it.
-Britt
Test-Driven-Development with SharePoint 2010 By Andreas Rudolf Aschauer, BSc
Andreas Aschauer studied Software Engineering at Vienna Technical University. Besides his studies he worked as a developer and consultant for .NET framework based solutions for various international corporations. Since 2009 he is a Development Trainer at ppedv GmbH with a strong focus on ASP.NET and SharePoint classroom courses. As the founder and co-owner of CodeForce he develops and consults real world SharePoint Solutions. As an active blogger for the Microsoft Developer & Platform Group and as a speaker on numerous conferences he shares is expertise on SharePoint and classical Software Engineering Processes / Practices.
The Article was written and translated to English by Andreas Aschauer, was published originally at
Andreas Rudolf Aschauer, BSc.
Test-Driven-Development with Sharepoint 2010
Adhering to the principles of clean Software Design is not always an easy task. Using and understanding how to apply Software Engineering Principles to real world projects makes the difference between a programmer and a Software Engineer.
The Microsoft SharePoint Platform and its API’s introduce a new challenge for developers building solutions on top of it. Creating loosely coupled, testable components for SharePoint is a non- trivial task. Most software relies on the existence of a physical SharePoint Farm, which stands in sharp contrast to the goals of Clean-Code Development.
Test-Driven-Development
Let us first take a look at TDD in general and who it is done, before examining the special challenges introduced with TDD on SharePoint.
Test-Driven-Development is an iterative process. Contrary to a legacy approach where production code comes first and is then validated by Unit Tests, the Unit Tests in a TDD style development process always come first! The tests reflect the specification and the assertions made, express the expectations we have, when the system is in a given context.
The whole iterative development process is known as Red- Green- Refactor Cycle. See fig. 1
- Red: Starting with a test, the test is red, because the production code doesn’t even exist
- Green: From developing the test, it is clear what classes, fields and methods are required to satisfy the test. Production code is implemented until the test is green. Only the minimal implementation that turns the Unit Test to green shall be produced! No overhead code.
- Refactor: After the expectations, expressed through the test have been met by the code, it is time to refactor and apply the “Software Engineering Principles” (see Box).
Software Engineering Principles
DRY, YAGNI, KISS... do those acronyms sound a bell? They are the ground rules for good software design. Don’t Repeat Yourself, You Ain’t Gonna Need It, Keep It Simple and Safe – with all these principles in mind source code becomes cleaner, better maintainable and that implicitly leads to higher quality. Take a look at some code from one of your past projects and you will see – There’s always work to be done!
Scanning your code for the violation of the Software Engineering Principles is an important step in Test-Driven-Development and – besides the Unit Tests themselves – the most important mean to improve software architecture.
The beauty of TDD lies in the fact that all code is instantly validated against the specification by the Unit Tests. Also the design – the architecture – is greatly influenced by this programming style. Everything tightly coupled or tied to external systems cannot be tested and thus has to be reengineered. Because we always start with the tests, we get an “external” view on the system to be developed and its components. From the very beginning on, the developer has to create a good, loosely coupled design, to be able to separate the various “modules” and test them isolated. To achieve that, programming against Interfaces – not concrete implementations – is the right way.
Test-Driven-Development with Sharepoint
Removing dependencies on external systems is one of the greatest challenges in Test-Driven-Development. Simulating systems and objects is known as Mocking or Stubbing.
Every developer who has already worked with the SharePoint Object Model knows how tightly coupled custom code is with the underlying SharePoint infrastructure. Even the most basic code, is intrinsically tied to an external system – SharePoint in this case. Take a look at the following extremely simple code snippet, which in most cases is the “entry point” into the object model.
public static SPSite GetSiteCollection(string url)
{
//Entweder explizit
return new SPSite(url);
//Oder via SPContext bei WebParts etc.
return SPContext.Current.Site;
}
This simple method call is enough hardwire our code to an external dependency and wipe out the possibility of context-agnostic, automated testing. As SPSite does not implement any interface, it is also nearly impossible (only with great, time- consuming effort) to mock this dependency. Using a Mocking- Framework is the only feasible way to develop TDD-style with SharePoint.
Typemock Isolator for SharePoint, provides the functionality needed for SharePoint developers to conduct serious Unit-Testing and develop high quality production code. Recommended by Microsoft Patterns & Practices it is the framework of choice for the task at hands.
Typemock Isolator can swap instances of objects at run-time. The framework substitutes real instances of SharePoint objects for mocked instances, whose behavior and return values can be defined in many ways. With Typemock Isolator in the toolbox it is possible to conduct real Test-Driven Development. We are able to run Unit Tests separated from a real SharePoint system. More important; we can now also create a System-Under-Test in memory. Unit Tests should never rely on any context created by another test and should always create and tear down the context needed for the assertions to be done.
Let’s take a look at a simple demo to learn about the “TDD development-flow” and the how to leverage Typemock Isolator for SharePoint development in C#.
Sample Scenario
The sample is intentionally kept simple to showcase the steps. The following tasks needs to be done:
A SharePoint list is filled with data from an import run. The list contains a (Text) field with an E-Mail address. Whenever a new item is created through import, an email should be sent to the E-Mail address.
To react to the list event a List Item Event Receiver can be used, that fires when a new item is created.
To create an Event Receiver select File -> New Project and chose the Event Receiver Template from the SharePoint tab. In the following wizard select “Sandboxed Solution” as a deployment type and choose the list template for the event receiver. For the sample choose “Task List” as list template and “An Item was Added” as the event type.
We want to develop TDD-style, so we add another class library project to our solution which will host the test code. To be able to work with Typemock Isolator, add a reference to Typemock. Arrange Act Assert.dll to the test project. Figure 3 shows the solutions structure.
Now it’s time to start implementing the specification, consisting of three methods.
1.) Parse the email address from the list element
2.) Validate the email address format
3.) Send the email
That means, we write the first unit test, that expresses the context in which the system is and our expectations about the behavior.
public class When_a_new_task_is_created
{
[Test]
public void Then_the_email_address_field_should_be_parsed_for_an_adress()
{}
}
The class and method names might seem a little unusual; they follow the idea of Behavior-Driven-Development. (see Box)
Behavior Driven Development
Behavior Driven is a way of naming test cases and classes in natural language. That way, when looking at the results of a test run, it becomes clear, from the names of the tests what functionality a test validates.
The names of the test classes express the context or situation and the test cases express the desired behavior.
Our first test is a structural one. It validates whether the method that parses out the email address from the list element called at all. That seems trivial in the sample, but when developing with a Dependency Injection Container it becomes important to verify whether the right methods of the right instances have been called.
Purists would now implement the whole test and only then derive the classes and methods needed in the production code from the test. For sake of article length we assume the code is already there.
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
var emailAddress =
GetEmailAddress(properties);
}
catch (Exception ex)
{
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithError;
}
}
public string GetEmailAddress(SPItemEventProperties properties)
{
try
{
var address =
properties.ListItem.GetFormattedValue(emailFieldName);
return address;
}
catch (Exception)
{
throw new ArgumentException
("Field '" + emailFieldName + "' not found in list");
}
}
From the code snippet it becomes clear that isolating an testing GetEmailAddress(..) is not trivial. We have a dependency on SPItemEventProperties. To simulate this „external system“ we can now use Typemock Isolator. Using a fluent, intuitive syntax we can fake a complete instance using the generic call Isolate.Fake.Instance<SPItemEventProperties>(). To control the behavior and mock method return wird Isolate.WhenCalled(..) can be used which accepts a Lambda Expression as an argument. To verify if a method has been called on our mock object Typemock Isolator provides Isolate.Verify(..) which also represents the assertion for our testing framework. This is all that is needed for our test to be readily implemented.
[Test]
public void Then_the_email_address_field_should_be_parsed_for_an_adress()
{
//Arrange
_receiver =
Isolate
.Fake.Instance<TaskListMailerEventReceiver>(Members.CallOriginal);
_fakeSpItemEventProperties =
Isolate.Fake.Instance<SPItemEventProperties>();
Isolate.WhenCalled(
() => _fakeSpItemEventProperties
.ListItem.GetFormattedValue(„Email Adress“))
.WillReturn(„office@codeforce.at“);
//Act
_receiver.ItemAdded(_fakeSpItemEventProperties);
//Assert
Isolate.Verify.WasCalledWithArguments(
() => _receiver.GetEmailAddress("", null))
.Matching(args => (args[0] == _fakeSpItemEventProperties));
}
First we create a mocked instance of the ItemEventReceiver and specify that all calls should be routed to the original implementations. The behavior for the mock of SPListItemEventProperties is determinded with Isolate.WhenCalled(..). In this case GetFormattedValue(“Email Address”) should return “office@codeforce.at“. Now we have completed stripped out the dependency on SharePoint and this Unit Test can run separately on a Continuous Integration Server.
The assertion is done afterwards an verifies that the method was called with the exact arguments passed in by the EventReceiver in the event handler. This is done with a call to .Matching(..) that accepts a lambda expression to check the args[].
An common task when working with SharePoint lists and list fields is the error handling logic around missing fields or misspelled field names. The following code snippet shows how to raise an exception and validate if the correct error handling in the ItemAdded(..) event handler.
[Test]
public void Then_an_exception_should_occur_when_adress_field_is_malformed()
{
//Act
Isolate.WhenCalled(
() => _fakeSpItemEventProperties
.ListItem.GetFormattedValue(EmailAddressFieldName))
.WillThrow(new System.ArgumentException());
_receiver.ItemAdded(_fakeSpItemEventProperties);
//Assert
Assert.That(_fakeSpItemEventProperties.Cancel == true);
}
The method WillThrow(..) ensures that the call to GetFormattedValue(..) throws an ArgumentException, which is exactly what will happen in the real system when the field is missing or misspelled.
The validation of the email address format is part of this article as this can be easily tested without mocking, there is no external dependency involved.
The third issue however is interesting in terms of mocking. Sending an email is done via a static class called SPUtility. Typemock Isolator supports faking static classes and methods via Isolate.Fake.StaticMethods(..). If the class itself is static (ie. not only the methods) the static constructor must also be faked with Isolate.Fake.StaticConstructor(..).
The following unit test shows how to fake a static class and a static method call and validate if the static call was made with any arguments given.
[Test]
public void Then_an_email_is_sent()
{
//Arrange
//Fake static SPUtility
Isolate.Fake.StaticConstructor(typeof(SPUtility));
Isolate.Fake.StaticMethods(typeof(SPUtility), Members.CallOriginal);
Isolate.WhenCalled(
() => _fakeSpItemEventProperties
.ListItem.GetFormattedValue(EmailAddressFieldName))
.WillReturn(„office@codeforce.at“);
//Act
_receiver.ItemAdded(_fakeSpItemEventProperties);
//Assert
Isolate.Verify.WasCalledWithAnyArguments(
() => SPUtility.SendEmail(_fakeWeb, false, false, EmailAdress, "Test", ""));
}
Further capabilities
Typemock Isolator also allows to automatically swap all future instances of a class with a fake with
Isolate.Swap.AllInstances<SPWeb>().With(Isolate.Fake.Instance<SPWeb>()). Furthermore Isolator can be used to fake private Methods. There is no need to make private methods visible to other assemblies, Isolator can find them via Reflection.
Typemock Isolator can do a lot of things and the full version also is not limited to the SharePoint Object Model but can be universally used across every .NET Assembly.
![summer-sale-header_03[1] summer-sale-header_03[1]](http://lh5.ggpht.com/_DWD9uJsgZOw/TF-e6KGFEYI/AAAAAAAAAKA/Rp6iplB4bto/summer-sale-header_03%5B1%5D%5B8%5D.jpg?imgmax=800)
