#programmierung

Posts tagged programmierung

Unit testing with mocks (Part 1)

I regret not having blogged on TDD and designing for test before – it makes it very difficult to talk about mocking as it is a rather advanced topic, requiring at least some knowledge of polymorphism and oo-design.
So this post is the first in a series of posts on the topic of testing with mock objects, that will hopefully help you with your testing.

Testing is one of the most important things in software development.
We’re all human, and we all make mistakes. And even if we discover these mistakes during development and testing, it’s almost certain that we’ll have to come back at a later point to change something, possibly breaking what already worked.
Doing a full QA cycle during initial development may look reasonable to most of us, but doing it every time you change a tiny bit in the application will certainly get you some angry mails from management.
Having good unit tests gives you a safety net for future development. By simply running the tests you can verify that things that already worked still work properly. And that’s what is important in software development.

The whole idea of unit testing is to test as little as possible while still verifying that the method under test behaves as specified and expected.
Keep this in mind, because it is important when testing classes that depend on services or other classes.

If let’s say you have a HttpServiceWatcher that is a service running somewhere and watching if a HttpService is up and running, you should test the HttpServiceWatcher class itself, not the associated notifier classes that the Watcher calls when it wants to notify you.
But how do you verify that the HttpServiceWatcher really worked and called the notifier as a result?

Let’s start with the Notifier interface:

public interface IErrorNotifier
{
    void NotifyOfServiceDown();
}

Let’s assume we have implemented a EmailNotifier class, if the HttpServiceWatcher looks like this we’re in testing-nightmare land:

public class HttpServiceWatcher
{
    public void ObserveService()
    {
        IErrorNotifier notifier = new EmailNotifier();
        notifier.NotifyOfServiceDown();
    }
}

The HttpServiceWatcher news up it’s notifier service, so every time we want to adjust the notifier, we’d have to change the ServiceWatcher and risk breaking something. Also, we can’t test the ServiceWatcher itself, because it will always call to an EmailNotifier that we can’t fake easily.

So, the correct move would be to use Inversion of Control (IoC) to inject the service into the watcher class:

public class HttpServiceWatcher
{
    private IErrorNotifier notifier;

    public HttpServiceWatcher(IErrorNotifier notifier)     {         this.notifier = notifier;     }

    public void ObserveService()     {         notifier.NotifyOfServiceDown();     } }

Now, the HttpServiceWatcher class doesn’t directly depend on any concrete implementation of IErrorNotifier, the calling code takes care of creating the concrete classes. Changes to notifiers don’t get propagated to the HttpServiceWatcher.
Also, this makes it very easy to simply fake the notifier. We could either create a fake test class that inherits IErrorNotifier, or we could use a Mocking framework.

Manual mocking could look like this:

public class NotifierMock : IErrorNotifier
{
    public int notifyOfServiceDownCallCount = 0;

    public void NotifyOfServiceDown()     {         notifyOfServiceDownCallCount++;     } }

The test could then look like this:

[Test]
public void ServiceWatcherNotifiesUser_Custom_Mock()
{
    var notifier = new NotifierMock();

    var watcher = new HttpServiceWatcher(notifier);     watcher.ObserveService();

    Assert.AreEqual(1, notifier.notifyOfServiceDownCallCount); }

And that’s fine. It works, we verify that the watcher actually calls the notifier service, and all is well.
It just gets tricky when you get more tests, you’ll have to create many mock objects that always introduce the possibility of breaking other tests etc.

In the next post in this series I will try to illustrate how to do the same thing with RhinoMocks and how it makes testing very easy.

Download the source code from my SVN Repository by doing a:

svn checkout https://office.pixelpoint.at:8443/svn/tigraine/UnitTesting/trunk UnitTesting –username guest

Continue reading Unit testing with mocks – Rhino Mocks basics (Part 2)

Read more →

Common gotchas with Inherited Forms

Don’t repeat yourself is one of the most important principles I know of. And there are many ways to follow DRY when it comes to normal code.

But when you go to Winforms-land most people forget about DRY and create the same Gui code over and over again. Some of them are clever and abstract the “handlers” away from the buttons, but they still draw most of the buttons multiple times for forms that look almost exactly the same.

But it’s pretty common to have multiple views of the same forms. Like a CreateNewUser and a UpdateExistingUser mask, they both share almost all textboxes, but their values get processed differently.

You could try to use the same form for both operations, but that violates SRP (and makes things a lot harder), or you have two different forms that inherit the controls from a parent form.

Tha't’s then called Visual Inheritance. And, sadly the Windows Forms designer within Visual Studio is pretty bad at it, it crashed on my multiple times.

After 2 hours of fooling around with the Designer to get my Forms to show again I decided to share my experience, since there are some simple rules that you can follow to not break your design surface:

Don’t remove the default constructor from your parent form

The designer depends on a parameterless constructor, if you want to have parameters create a new constructor (and therefore don’t forget to call InitializeComponent again)

Don’t hook up Form_Load events in your parent form

I sincerely have no clue why this breaks the designer, but it does.

 

It’s rather tragic that the designer breaks on working code (compiling and running my code always worked, the designer just couldn’t load the form to show the design surface), but if you follow the above guidelines everything should work out fine.

There is also another way to remove code duplication by using Custom Controls and User Controls, these get handled better by the designer, but require a bit more thinking when creating (You may get in trouble when you try to modify their instantiation because that’s done during the InitializeComponent call).

Read more →

Sourcecontrol and Databases, when ORM comes in handy

I encourage every one (even single developers) to use a Sourcecontrol system such as SVN and AnkhSVN to do development. Put all your project files (and external dependencies) under source control and maybe even get a continuous integration server setup.

And still, even if you’ve done all of this, chances are high you still have one external dependency in your project: the Database!

And this is where the pain starts, if you don’t find some way how to put your DB schema under source control too, you’ll end up going back to old versions and having no database of that date.

There are however several ways to solve this that I can think of:

  • Make your CI server fetch a schema script every time a build is triggered.
  • Make creating a schema script part of your build process

And .. guess what? There’s a simpler way :).
If you’re using a ORM tool you should always have your database model somewhere in the mapping files.

Because the mapping files tell the ORM the structure of the DB, they essentially contain all relevant information needed to generate a schema without the need to have SQL scripts.

In NHibernate for example, you can simply do a:

var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof (Person).Assembly);

new SchemaExport(cfg).Execute(false, true, false, false);

And the mapper will go out and create all necessary tables and relationships in your database.

By having an ORM capable of recreating the schema, I no longer need to keep the Database itself under source control, because the necessary information to recreate the schema is already in my source tree.

Read more →

DecimalTextbox for Windows Forms

I’ve been doing some Windows Forms development lately and really love it. After doing web development for the last couple of years I am thankful for the change. Being able to create compelling UIs without having to worry about Javascript is something I’ve been longing for quite some time.

But when trying to build intuitive and user-friendly UIs, you hit the boundaries of Microsoft’s control toolbox pretty fast. (Not as fast as with Webcontrols, but still).
I needed a Textbox that accepts only decimal input and that formats itself rather nicely for a finance application I’m building right now.

I first turned to the MaskedTextBox control that’s already there, but that turned out to be completely useless because numbers have no fixed length.
So I decided to create a Custom Control that derives from TextBox that does exactly what I need – take decimals and nothing else.

The whole process is rather simple, so I’ll just give you the code and be done with it. The DecimalTextbox control won’t accept any input that’s not numeric except for one comma. If you leave the control empty or non-decimal (however you accomplish that) it will revert to 0,00 on validation.

The code is after the break

public partial class DecimalTextBox : TextBox
{
    public DecimalTextBox()
    {
        InitializeComponent();
    }

    protected override void OnTextChanged(EventArgs e)     {         if (IsDecimal())             base.OnTextChanged(e);     }

    protected override void OnKeyPress(KeyPressEventArgs e)     {         if (!char.IsNumber(e.KeyChar)             && ((Keys)e.KeyChar != Keys.Back)             && (e.KeyChar != ','))             e.Handled = true;

        if (e.KeyChar == ',' && Text.IndexOf(',') > 0)             e.Handled = true;

        base.OnKeyPress(e);     }

    protected override void OnGotFocus(EventArgs e)     {         ResetValueOnFocus();         base.OnGotFocus(e);     }

    private void ResetValueOnFocus()     {         if (IsDecimal())         {             if (!IsDecimalZero())                 return;         }         Text = "";     }

    private bool IsDecimal()     {         decimal result;         return decimal.TryParse(Text, out result);     }

    private bool IsDecimalZero()     {         return (decimal.Parse(Text) == 0);     }

    private void DecimalTextBox_Validating(object sender, CancelEventArgs e)     {         decimal value;         decimal.TryParse(Text, out value);

        const string NUMBER_FORMAT_2_DIGITS = "N2";         Text = value.ToString(NUMBER_FORMAT_2_DIGITS);     }

    public decimal Value     {         get         {             return decimal.Parse(Text);         }     } }

And since copying source from HTML sucks here’s the DecimalTextBox.cs.

Read more →

Come to the dark side – we have cookies

vibrantink

After looking at the default color settings of Visual Studio for the last 8 years of my life I finally decided to give Rob Conery’s Vibrant-Ink theme for Visual Studio a try.

I discovered this lovely little theme quite some time ago, but I really didn’t see any benefit from changing my settings to this, so I forgot about it.
Until recently I started to feel the pain of working 10+ hours on a mediocre screen.
Eye strain was quite bad, and when someone suggested the theme (again) at Stackoverflow I finally tried it.

And, I have to admit, not only does my VS now look way cooler. My eyes feel less tired after long hours of work.

I would definitely suggest trying the theme, it’s just incredible.

Get the theme over at Rob Conery’s Blog and maybe adjust it a bit like Andrew Stopford suggests. But still, stick with Consolas as your font!

Read more →

Log4Net – Logging made easy

I confess, I’ve done projects that have Console.WriteLine or Debug.Print written all over the place. Sometimes I encapsulated that stuff into a separate Log Class that got passed around to every one, or sometimes I just created this little singleton that did the logging.

Either way, it was code I didn’t really want to write until late in development where I had to go back and retrofit logging into the application. And almost every time I did this it sucked and wasn’t satisfying at all. It worked, but I could have spent countless hours on polishing the logging stuff.

That was until I found Log4Net, the .NET implementation of the open-source log4j framework.

Log4Net enables you to just forget about the logging altogether while you develop your application. Just categorize your log statements into the 5 prioritized levels (DEBUG, INFO, WARN, ERROR, FATAL) and think about the configuration some other day.

Log4Net is completely Xml configuration driven and provides a very high degree of extensibility (Just implement new Appenders, Filters or Layouts).
So it keeps decisions about the where/how/when to log absolutely open until the very end.

Hell, you can even configure a file watcher and change the Log4Net Xml configuration during runtime!

Log4Net has just made it to my imaginary “must reference in each project” list. I strongly suggest you check it out.

Read more →

Handling dependencies

After playing around with Log4Net and the Castle MicroKernel, I suddenly discovered that not having those external dependencies under source control makes development quite difficult.

Whenever I update my dependencies, all other people on the team need to adjust theirs to match mine and vice versa. This is a minor annoyance while the team is small, once you grow and have people coming in and out of the team you’ll start to feel real pain!

If sucks even more if you’ve already shipped your application and get called a year later to change something. Trust me, digging up the right version of library X isn’t getting easier over time, and updating the application to a new version may either break the application or cause your customers to update too (both highly undesired!).

So, what’s the right solution to dependencies?
(No it’s not reinventing the wheel over and over again by writing everything by yourself)

Simple: Put the dependencies into a folder called /lib/ and reference them from there, set the “Copy To Output Directory” option to “Copy if newer”.
Then add this folder to your source control and you’re set. Whenever a new guy comes to the team and gets the project from source control, he’s guaranteed to be able to build it without having to run around some random site searching for referenced assemblies.

Read more →

Using Extension Methods as a Factory Method for an Adapter

Sometimes you have existing code you don't want to change. And sometimes you need to write libraries that consume these old legacy objects as input to function.
No need to say that it's usually a bad idea to couple your code to not properly tested and poorly designed legacy code.

So it's generally a good idea to abstract it away from new code and try to mask the old objects through adapters and interfaces from being too tightly coupled to your new code.

Either way, you're trying to put square blocks into round holes. And the adapter classes need to be initialized by your callers every time your class gets used.

    public class LegacyFoo
    {
        public void SomeFoo()
        {}
    }
    public interface IFoo
    {
        void Foo();
    }
    public class FooAdapter : IFoo
    {
        private readonly LegacyFoo Foo_;
        public FooAdapter(LegacyFoo foo)
        {
            Foo_ = foo; }
        public void Foo()
        { Foo_.SomeFoo(); }
    }
    public class FooConsumer
    {
        public void DoSomethingWithOldFoo(IFoo oldFoo)
        { oldFoo.Foo(); }
    }

So instead of providing yet another Factory that constructs the adapter object, you could instead just put the factory method onto the legacy object by using an extension method:

    public static class FooExtensions
    {
        public static IFoo GetFooAdapter(this LegacyFoo foo)
        { return new FooAdapter(foo); }
    }

Now your callers can conveniently construct the Adapter object by calling:

LegacyFoo foo = new LegacyFoo();
foo.GetFooAdapter()

Read more →

The deprecated target attribute and jQuery

It's usually not considered polite to open new windows whenever somebody clicks one of your external links. Those back and forward buttons are there for a reason, so I strongly encourage people to avoid opening new windows.

But, we all know customers. They get this "but I want this" look the second they discover that users may leave their web site too early (can't say how much this attitude sucks..).

One popular way to do this is to use jQuery to open all external links on your page in a popup (making code that obviously violates the "don't open new windows" rule still validate).

$(document).ready(function() {
    $("a[rel='external']").click(function(event) {
        window.open($(this).attr("href"));
        event.preventDefault();
    });
});

Now all you have to do is, add a rel="external" attribute to all outgoing links, and this little jQuery function will take care of making them popup.

Still, this is bad. It contradicts the whole idea why they removed the target attribute in the first place, so consider this as a quick'n'dirty hack to satisfy stupid customers.

Read more →

Anatomy of a pattern: Singleton

Singleton is one of the simplest patterns that does just one thing: Ensure that there is one object to rule them all, one object to bind... (Ok sorry got dragged away).

The idea is simple: Sometimes (especially when writing to disk with open file handles) you need to ensure that there is only ONE instance of a class going on at any time. And that's it. It's so simple, you could turn it into a 1-liner:

public static Singleton _Instance;

But things never are that simple ;). By using only a shared variable you may end up calling the constructor twice, resulting in 2 objects that may get used by two different clients.

To avoid this you'll need to get an exclusive lock of the Singleton to ensure it's really empty before you instance it.
And that's how it's usually done

private static Singleton _Instance;
private static Object __LockObject = new object();

public static Singleton GetInstance() {     if (_Instance == null)     {         lock(__LockObject)         {             if (_Instance == null)                 _Instance = new Singleton();         }     }     return _Instance; }

In the singleton implementation the static Singleton variable holds the reference to the Singleton, and whenever we try to get a reference to this instance we check if it's already set and return the value.

If not, it get's tricky when 2 threads are getting a cache-miss at the exact same time (_Instance == null). If you aren't synchronizing at this point you may end up with two different references of a singleton object being used (and causing problems with resources being consumed twice, causing ). So it's important to perform another check when you have exclusive reign over the shared object (by using a lock object here).


This ensures that no two threads will try to create a new instance to your singleton, while not slowing down your read-performance at all.

Sample code: Singleton.cs

Read more →