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?
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();
}