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!
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.
精彩评论