C#: How to test asynchronous events

The other day I had to test that an event was raised after some asynchronous work had been done. And since I currently am a total test newbie, this was a new thing for me. Say we have this simple shell of a class:

public class Worker
{
    public event EventHandler<eventargs> Done;

    public void Start()
    {
       ...
    }
}</eventargs>

Let’s just assume it does some work, and is supposed to raise the Done event when it is… well… done.

Continue reading

C#: Generics and checking for null

When writing C#, in Visual Studio, using generics… have you ever tried checking for null? I have always found that a bit of a hassle.

Say we have this method which returns the subject if it is not null, and the result of a createNew() function if it is null.

public static T NewIfNull<t>(this T subject, Func</t><t> createNew)
{
    if (subject == null)
        return createNew();
    return subject;
}</t>

Not claiming this is a very useful method, but it was the simplest thing I could come up with :P Anyways, in Visual Studio you will now probably have a blue (is blue here at least) squiggly line under the equality operator. It states you are doing a Possible compare of value type with ‘null’, which of course is reasonable and correct. We could just ignore it and move on… but we don’t really like squiggly lines, do we? I sure don’t… so lets get rid of it.

Continue reading

Project Euler: Problem 25

The Fibonacci sequence is defined by the recurrence relation:

F_n = F_{n-1} + F_{n-2}, where F_1 = 1 and F_2 = 1.

Hence the first 12 terms will be:

 F_1 = 1 \\ F_2 = 1 \\ \ldots \\ F_{11} = 89 \\ F_{12} = 144

The 12th term, F_{12}, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

Continue reading

The Art of Unit Testing

The Art of Unit Testing (Book cover)Have you gone through three years of computer science bachelor degree fun (or anything similar) and pretty much not heard a word about testing? Or have you heard from all your teachers that testing is extremely important, but never learned how to even write one? That has been the case for me. Testing is important, you all got to do it, it is very important, always test, do it a lot! Well, sure… but how do I do it? How do I write one of these tests?

Continue reading