Sai
Sai

Reputation: 712

Unit testing a void method that writes to a file and doesn't mutate any class members

I need to unit test a protected method since it has some core logic(I can't change this part as it is not in my control). It doesn't change any members so can't write assertions based on that. It doesn't return anything except reading from a registry and write to a log file. How can I write a unit test with Moq and VisualStudio NUnit testing for this scenario:

protected override void OnPluginStarting()
{
    try
    {
        using (var key = registryAccessor.LocalMachine.OpenSubKey(ProdInstallRegKey))
        {
            foreach (string subkeyName in key.GetSubKeyNames())
            {
                using (var subkey = key.OpenSubKey(subkeyName))
                {
                    string displayName = subkey.GetValue("DisplayName") == null ? string.Empty : subkey.GetValue("DisplayName").ToString();
                    if (!string.IsNullOrEmpty(displayName) && installedProducts.ContainsKey(displayName))
                    {
                        Log.Info(installedProducts[displayName] + " version is " + subkey.GetValue("DisplayVersion"));
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Log.Error("An error occured while getting the version numbers of DDP components. "+ex.Message);
    }
}

RegistryAccessor is a wrapper for the Registry and I have used it so that I can mock it from my unit tests. But how can I pass the mock registry object to the method when it does not take any params? The only things I have figured out is that I can use PrivateObject to create private and protected instances. Could someone please help?

Upvotes: 0

Views: 91

Answers (2)

AD.Net
AD.Net

Reputation: 13399

You should have someway of injecting registryAccessor and logger, that way you can control what the code reads from registry and confirm the output by checking the call to the logger.

Otherwise you can try some integration tests (probably more difficult in your case) or something like TypeMock

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59218

You can't.

There are commercial tools like TypeMock that use the Profiler API to achieve things like that. This will allow to intercept sealed classes, static methods etc.

Upvotes: 0

Related Questions