Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to unit test a lazy load property

I'm somewhat of a newbie in unit testing. Stumbled upon a problem of unit testing a lazy load property and wondering if there is a simple solution to that:

private SubscriptionType _subscriptionType;
public SubscriptionType SubscriptionType
{
    get
    {
        if (_subscriptionType == null ||_subscriptionType.SubscriptionTypeId != this.SubscriptionTypeId)
        {
            if (this.SubscriptionTypeId !=0)
                _subscriptionType = SubscriptionType.Load(this.SubscriptionTypeId);
        }

        return _subscriptionType;
    }
}

I need to test logic in the property (if statements) and not the actual SubscriptionType load functionality - seems like the most obvious approach here would probably be to abstract SubscriptionType.Load and use some type of IoC to replace with a mock method. I'm just wondering if there are any simpler ways to avoid this kind of refactoring - seems like somewhat of an overengineering just to write a correct unit test case. Your thoughts? Thanks!

like image 896
DSY Avatar asked Apr 19 '11 00:04

DSY


People also ask

How do you test lazy loading?

If you're not sure if lazy loading is working correctly, you can open the Chrome DevTools and check that the images are not loaded until the scroll.

Should I unit test properties?

Generally, no. A unit test should be used to test for the functionality of a unit. You should unit test methods on a class, not individual, automatic properties (unless you are overriding the getter or setter with custom behaviour).

What is lazy loading in selenium?

The concept of delaying the loading of an object until one needs it is known as lazy loading. In other words, it is the process of delaying the process of instantiating the class until required.


1 Answers

Unless you want to use TypeMock Isolator or Moles you'll have to hide the Load method behind an interface and inject that into the class. There's no way around it, but you'll not only be doing it for the sake of testability. Usually you also tend to get better separation of concerns out of such a refactoring.

like image 61
Mark Seemann Avatar answered Oct 08 '22 04:10

Mark Seemann