Friday, August 27, 2010

Typemock Sponsors See# Party 2010 (#ssp2010)

 image

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.

image

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

Thursday, August 26, 2010

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?

Gil Zilberfeld

Wednesday, August 18, 2010

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.

Wednesday, August 11, 2010

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 hand

Our 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 BusinessObject

I’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:

  1. Create a new data access layer
  2. Create a new BusinessObject
  3. Call Save
  4. 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:

image 

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 logic

What 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:

image

That’s it. The very basics of Isolator++.

More information on faking objects can be found on Isolator++ online user guide

Happy coding

Dror B. Helper

Monday, August 9, 2010

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.

Lior Friedman

Typemock Summer Sale

summer-sale-header_03[1]

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!

Gil Zilberfeld

Wednesday, August 4, 2010

Typemock Sponsors #devLink2010, August 5 - 7th

devLinkLogo400 

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 

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

Friday, July 30, 2010

Typemock Supports #SharePoint Saturday NY #SPSNY

image 

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

Tuesday, July 27, 2010

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 bettc[1]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! 

Friday, July 23, 2010

How do you test asynchronous code? Part II

This is the second part of Stefan Lieser’s article appearing in DotNetPro. Stefan was generdot_Logo_SchwarzRot_170_41ous 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 Stefan-Lieserand 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.




Gil Zilberfeld

Thursday, July 22, 2010

SharePoint Down Under

launchbanner 

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.

ElaineWe 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

Tuesday, July 20, 2010

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.

Gil Zilberfeld

Monday, July 19, 2010

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 WildGil Zilberfeld
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,

 

Tal Druyan

Friday, July 16, 2010

How do you test asynchronous code? Part I

This is the first part of Stefan Lieser’s article appearing in DotNetPro. Stefan was generdot_Logo_SchwarzRot_170_41ous 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 Stefan-Lieserand 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

}



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;



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;

}



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;

}



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")]



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;

}



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.









Gil Zilberfeld

Thursday, July 15, 2010

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?

Lior Friedman