I have a method for which I'm going to write unit test. The simplified version of method:
public static bool IsUpdateAvailable()
{
Version installedVersion = Util.GetInstalledVersionFromRegistry();
Version availableVersion = Util.GetAvailableVersionFromRemote();
bool isRemoteVersionNewer = IsVersionNewer(installedVersion, availableVersion);
return isRemoteVersionNewer;
}
So the problem is to make two local variables (installedVersion, availableVersion) read their values not from real sources (in this case from registry and internet) but from some kind of fake source. I'm not able to modify the above mentioned method. And I'm trying to understand how I can mock that two variables by using for example Moq or Microsoft Fakes. I did search over the internet but was not able to find some related sample code. So how I can mock the local variables of above mentioned method and test that method?
It's the same problem with every static and hard coded dependencies. Try to avoid static wherever you can and classify it bad in the first place. Develop real arguments for marking something as static and not because R# told you so.
How to solve this is via Dependency Injection. You have to inject the dependencies via parameters to make it testable.
ctor(Version installedVersion, Version availableVersion) {
// Maybe store them in private fields.
}
public bool IsUpdateAvailable()
{
bool isRemoteVersionNewer = IsVersionNewer(installedVersion, availableVersion);
return isRemoteVersionNewer;
}
I guess you now see, that you don't have to mock the variables itself. You can just create different instances of your object with different inputs. One that constructs the object with your Util. methods and others with test data for your unit tests.
I also propose dependency injection, if you can do it . If you cant, to solve this particular problem you can use shims.
http://msdn.microsoft.com/en-us/library/hh549176(v=vs.110).aspx#bkmk_static_methods
You mentioned you cannot do any modification to the function. I am proposing a change, but as you will see it does not matter much.
(Code is not compiled or tested)
public static Version GetInstalledVersionFromRegistry()
{
return Util.GetInstalledVersionFromRegistry();
}
public static Version GetVersionFromRemote()
{
return Util.GetAvailableVersionFromRemote();
}
public static bool IsUpdateAvailable()
{
Version installedVersion = GetInstalledVersionFromRegistry();
Version availableVersion = GetVersionFromRemote();
bool isRemoteVersionNewer = IsVersionNewer(installedVersion, availableVersion);
return isRemoteVersionNewer;
}
Testing using shims
using (ShimsContext.Create())
{
ShimYourclass.GetInstalledVersionFromRegistry=()=>new Version();
ShimYourclass.GetInstalledVersionFromRegistry=()=>new Version();
//test your class here
Yourclass.IsUpdateAvailable();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With