Browsing all articles in .NET Tests
May
10
Comments

Converting Dynamic Types to Generic Parameters

Author Eli Lopian    Category .NET Tests     Tags

There is a problem when an API uses a Generic Parameter as a Type reference.image Although having a generic parameter makes the code Type Safe

SafeType MyApi<SafeType>();

It is really hard to use the API in dynamic way. So if we receive a Type in a variable there is no easy way to call the generic method.

Type myType = GetTypeToUse();
var ret = MyApi<myType>();
//              ^^^^^^ Error

One way to do this (convert a dynamic type to a generic type) is via reflection (See example on the Typemock Blog)

private static object MyApi(Type ofType)
{
 MethodInfo myApiMethod = typeof(MyAssembly)
     .GetMethod("MyApi").MakeGenericMethod(ofType);
 return myApiMethod.Invoke(null, null);
}

or we can cache the MethodInfo

private static MethodInfo myApi = typeof(MyAssembly).GetMethod("MyApi");
private static object MyApi(Type ofType)
{
 MethodInfo myApiMethod = myApi.MakeGenericMethod(ofType);
 return myApiMethod.Invoke(null, null);
}

When designing an API we should think of developers who receive the Type in a dynamic way, and have an embedded API to handle this from the start.

// Type Safe API
SafeType MyApi<SafeType>();
// Dynamic Type API object MyApi(Type ofType);
Apr
1
Comments

Typemock Isolator goes open source

Author Eli Lopian    Category .NET Tests     Tags

Due to the overwhelming request by the community, we have receivedimage thousands of e-mails from .NET developers, that almost crashed our servers. And after we have had serious discussions with a large software company, we have managed to find a way that will allow us to open source Typemock Isolator for the benefit of the community (and of myself ;-)

It will take us some time to clean the code, but in the meantime we have uploaded the sources to codeplex, you can download them here.

[Update: Got-Ya! This is an April fools]

Dec
4
Comments

Unit Tests and Developers under Pressure

imageIn TechEd 2008 David Platt interviewed Roy about the future of  TDD. You should really view the Tech-Talk as Dave is really funny, although he does miss the number of possible TLA’s (which he recursively defines as a TLA = Three Letter Acronym) by 300.

About 5 minutes into the session David asks a key question: “What happens if your boss comes and says: I’m in a hurry, I need this, come on we need to ship this, we need to hurry up, forget about the tests“. What do you do?

I think that David has a valid point that is extremely important to address, as many teams are under pressure and they willing to find any excuses to ‘just code’. This question is going to define where we are going as a profession.

So what keeps us professional, what keeps us from doing cowboy development as Dave suggested that has been proven to lead us to more costs?

As Roy Said, it is a well defined process that will save ourselves from this pitfall, and writing unit tests is one of them. Just like professional teams will not even think of ditching their QA process, developer teams can not afford, in these economic times, to ditch unit testing. As a matter of fact, once you start unit testing you will find that you will be under less pressure!

You will spend some time writing tests (which you would have spent anyway on manually testing the application), but the ease at which you can continue to add functionality without breaking the code, will return that investment in no time. So the quickest way to implement a feature is actually using unit tests! I have seen so many teams make the mistake of not writing the tests, and within a few hours, they are already introducing bugs and are afraid to add features as they might (and probably will) break the code.

So back to Dave’s question, what happens if your boss is in a hurry? Be professional, just write the code and the tests as fast as you can. This is the most efficient way to write software.

Nov
24
Comments

Isolator for SharePoint – Free License

Get a free Typemock Isolator license:

[Update: Contest is finished, Thanks to all you bloggers]

We’re announcing today about a new product: Isolator for SharePoint. It is almost the same as Typemock Isolator, but will only work on APIs that are directly connected with sharepoint’s API. That means that if you only need to test sharepoint stuff, you can get a powerful product, for a much cheaper price than the full Isolator (you can always upgrade later if you need to isolate more APIs).

With this release, we want to gather the power of crowds, by offering you an incentive for blogging about this news: Get A free Typemock Isolator license (the full one) just because you have a blog. Here’s the official word:

Are you a blogger, webmaster, or Internet columnist? Get a Free Typemock Isolator License (Personal Edition) by helping us launch our new product, Isolator For SharePoint, the only tool that can unit test SharePoint applications without a SharePoint server – see the Microsoft Guidance.

Go ahead, post about it now and your Free License will be on its way!

So how do I get the Free License?

Just make a post on your blog or site about the latest Typemock product, that includes the following text:

Typemock are offering their new product for unit testing SharePoint called Isolator for SharePoint, for a special introduction price. it is the only tool that allows you to unit test SharePoint without a SharePoint server. To learn more click here.

The first 50 bloggers who blog this text in their blog and tell us about it, will get a Full Isolator license, Free. for rules and info click here.

Then please send an email to sharepoint@typemock.com including your name and the post URL, and your Free License will be on its way!

Hurry up – this offer is limited to the first 50 bloggers.

A few simple requirements:

(1) You must own a website, blog space or internet column, older than 2 months, or get permission from the owner of such a site.
(2) Your post must include the text above (including the links).

Nov
13
Comments

Unit Testing Collections

Author Eli Lopian    Category .NET Tests, TDD     Tags

loopI have written about Lowering the friction of Unit testing, and how using Aspect Faking we can lower the friction of testing collections

The problem

Unit testing collections can be a bit tricky. Lets see some code and unit test this Sum() method:


public List<Salary> Salaries { get; }

public float Sum()
{
    float total = 0;
    foreach (var item in Salaries)
    {
        total += item.Value;
    }
    return total;
}
public class Salary
{
    public float Value { get; set; }
    ...
}

Testing this can be simple: just supply a collection with fake items and run the code.


[TestMethod]
public void Sum_Adds3Items()
{
    var fakeSalaries = new List<Salary> {

        new Salary { Value = 5000 }, 

        new Salary { Value = 6000 }, 

        new Salary { Value = 5500 } };

    var payments = new Payments();

    payments.Salaries = fakeSalaries;

    Assert.AreEqual(16500, payments.Sum());
}

Simple, but in some cases, it is impossible to create the fake list. Examples are: Linq queries, SharePoints SPListCollection and SPItemCollection and DevExpress XPCollection. This are all custom collections and cannot be instantiated. We want to fake these collections, but we want to do it in a resilient way. Resilient enough that if we can choose to implementation via direct calls on the index without failing our tests.


public XpCollection<Salary> Salaries { get; set; }

...

float total = 0;

for (int i = 0; i<Salaries.Count; i++)
{
    total += Salaries[i].Value;
}
return total;

Here is where Faking the Collection Aspect comes into play, we want to fake just the Collection-Aspect the XpCollection and swap it with a collection of our choice.

Isolate.Swap.CallsOn(payment.Salaries).WithCallsTo(
   new[] {
        new Salary { Value = 5000 },
        new Salary { Value = 6000 },
        new Salary { Value = 5500 }
   });
Note how we are just passing an array!.

Now we can test our code and it won’t break if we change the implementation from using the enumerator of using direct access through the indexer.

This feature is soo useful that it got its own API:
 
Isolate.WhenCalled(() => payment.Salaries)
   .WillReturnCollectionValuesOf( new[]
   {
        new Salary { Value = 5000 },
        new Salary { Value = 6000 },
        new Salary { Value = 5500 }
   });

Once again, we manage to lower the friction of unit testing and create resilient tests.

Nov
11
Comments

Lowering the friction of Unit testing

Author Eli Lopian    Category .NET Tests, TDD     Tags

image At Typemock we have been learning allot about our customers lately and understanding where the friction is so that we can make unit testing even easier and maintainable.

What we are succeeding in doing is to lower the density of the tests (this means less code in each test) and raise the test resilient (this means the tests will still work after code changes)

Roy Oserove has talked about this (here, here and here). This has been the basis for the new API and concepts that we have already introduced in Typemock Isolator.

One feature that does this is the Recursive Fakes. Using this we fake and ignore a whole component, by faking a complete call stack. Our classic example is using SharePoint. In SharePoint a top most entry point is SPSite(). All other operations are a part of the call stack and objects returned from the SPSite.

example:

var site = new SPSite(); var web = site.OpenWeb(); var lists = web.Lists; var items = lists[1]; items[2].Update();

Note that SPSite is a Mother class of all other types.

We found out that in our tests, we normally don’t want to fail if any extra calls are called within this call stack. We also still want the test to pass if less calls are made within the call stack. Here is how we do it:

SPSite fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);

Using this will fake ALL the methods above, and all other methods that are called on the call stack of fakeSite! We can of course specify a fake value down the call stack:

Isolate.WhenCalled( () => fakeSite.OpenWeb().Lists[2].Items[1].Update). WillThrow(new Exception("");

Here we simulate an exception down the call stack, but all other calls will just work!

Thinking in the terms of Faking the call stack helps in writing less code in the test and adding to the resilient of the test. We are going to keep that trend as we continue to promote unit testing by enabling easy isolation.

Nov
9
Comments

Typemock embraces SharePoint

Author Eli Lopian    Category .NET Tests     Tags

We have been getting a lot of traction from the SharePoint development community about the ease that Typemock Isolator helps unit test SharePoint Applications.

image The Practices and Patterns Group in Microsoft have released a SharePoint Guidance that you can download the November 2008 version here. Typemock Isolator is being used as the primary isolating tool.

We are getting many great comments, here are some of the stuff we are getting

We are planning in creating a special package for SharePoint developers. Wait for the news on our SharePoint page

Nov
6
Comments

Ruby Style Isolating – Aspect Faking

Author Eli Lopian    Category .NET Tests, Product, TDD     Tags

I have talked in the past about Ruby Style Isolating (Dynamically Typed), now it is part of the AAA syntax

The big value of this feature is that you don’t have to inherit a type in order to replace it with a fake, the downfall of this is that when you refactor your code, you might fail the test.

There are many uses. One example is if you have a class without virtual methods,  you can still overload it and swap the real type with the fake one.

This gives you testability strengths and the ability to keep your design intact.

Example Suppose we have the following class:

public class NiceClassWithoutVirtual
{
    public int NonVirtualMethod()
    {
        return 30; // an example not virtual
    }
}

Now we want to use a manual Stub to replace our NonVirtualMethod: we can do the following: note the new before the method.

public class FakeNiceClass: NiceClassWithoutVirtual
{
    public new int NonVirtualMethod()
    {
        return 2; // our fake value in new not virtual method
    }
}

We can use the Stub as follows

var real = new NiceClassWithoutVirtual();
var fake = new FakeNiceClass();
Isolate.Swap.CallsOn(real).WithCallsTo(fake);

All real.NonVirtualMethod() calls will be directed to fake.NonVirtualMethod()

Fake an Aspect

Note that any methods that are not defined in the swapped type will be run as normal. This allows ‘Aspects’ of the original class to be faked. It is possible to fake a group of methods that have a specific meaning, for example just the ISerializable aspect or just the IEnumerable aspect – so we can fake the collection behavior aspect of a type. This is exactly how we implemented the Swap-Collections Feature

Nov
3
Comments

Future of Unit Testing and Economics

Author Eli Lopian    Category .NET Tests, Agile, TDD     Tags

Euan Garden managed the PDC 2008 Panel Session on the Future of Unit Testing, and Andrew has made a short summary.

Unit Test => (Automated) Developers Tests

An interesting thought that come from listening to this panel is that there is a confusion about what unit tests are and I agree that we should really call it (Automated) Developers Tests. This is one of the cases where Microsoft got it right when they called their developer testing tool msTest and not msUnit. Even so, I will continue to call these unit tests, but my meaning is for all tests that developers need to do.

I also agree that many developers still have the concept of “I am a developer so I don’t need to test my code – that is something that the QA team should do”.

Two Futures…

Watching the panel it is obvious that there are two paths that are being considered. The first is that we should not use any tooling at all, and that the pain of doing unit tests will help us write better code – (if you have any pain – it means that you are writing bad code, if you keep on having pain perhaps you are not a good developer), while the other camp say that testing is boring/complex, lets make it easier with tooling

Developer Testing Economics

There is a lot of economic sense in making developers testing there code early on, the early you detect a bug the cheaper it is.

image

So even without creating a better designed software there is still great value in developers testing their code. The thing is that most developers are not willing to test their code, it is too painful/boring. The future is that more and more developers will unit test the code as it cuts the costs of developing software, and that unit testing will be an industry standard. But what is going to make these developers start testing their code?

The Future – Unit Testing will be industry standard

I follow the Rails mantras of Opinionated Software, and my opinion is that we have to make unit testing easier for the masses to follow. It is great to see that Microsoft is also investing in tooling (Pex and TDD in Visual Studio 2010. Other vendors have these tools already – Parasoft .TEST).

The biggest obstacle for developers to unit tests is the need to isolate the code under test. Software is complex, which makes testing it complex. Using the divide and conquer technique to reduce the complexity of the tested unit will render testing these units simple.

Mocking frameworks today are not the same tooling they used to be, they are now isolation tools and these isolation tools will keep developing and progress and help developers focus on simplifying the task of testing their code.

May
19
Comments

Mocking frameworks – dream feature

Author Eli Lopian    Category .NET Tests, Product, TDD     Tags

imageThere are some developers SHOUTING, that mocking static and  non-virtual methods is a big No-No. Roy, is calling them dogmatic.

Come on guys, the most requested feature from Rhino.Mocks is the ability to mock non-virtual and static members, and Oren has even implemented these when possible (MarshalByRef Objects). I am sure that if it was easy, Daniel would do so too.

In other languages where objects can be swapped without Dependency Injection, there is no-one, calling these features – Bad Practice, just the opposite. They are called ‘Power features’, because that is what they are.

You might prefer to sweat and spend a lot of your time figuring out how to make your code testable, and you might find it easier in your company to introduce a free tool, but please, don’t call a tool that gives you lot of pain,  forces you to use DI (even if you don’t really need it) and to spend time creating utterly useless wrappers – a feature!