Pablo Pablo - 3 years ago 94
C# Question

Can I mock object which is impossible to instantiate?

I am using some COM library in my C# which is bound to particular hardware and doesn't work without it. On development/testing computer I don't have that hardware. The method which is using library looks like this:

using HWSysManagerLib;
bool ProcessBias(HWSysManager systemManager, string hwPath)
{
int handle = systemManager.OpenConfiguration(hwPath);
...
// some magic goes here
// return result
}


The question is, can I mock
HWSysManager
for test method and how? There are few methods only in
HWSysManager
and it wouldn't be problem to simulate their functionality for test. A tiny example would be great on how to mock it, if it's possible at all.

Answer Source

You can use the adapter pattern here.

Create an interface named IHWSysManager

public interface IHWSysManager
{
    int OpenConfiguration(string hwPath);
}

The real implementation class just delegates the work to the library:

public class HWSysManagerImpl : IHWSysManager
{
    private HWSysManager _hwSysManager; //Initialize from constructor

    public int OpenConfiguration(string hwPath)
    {
        return _hwSysManager.openConfiguration(hwPath);
    }
}

Use the interface in your code like this:

bool ProcessBias(IHWSysManager systemManager, string hwPath)
{
    int handle = systemManager.OpenConfiguration(hwPath);
    ...
    // some magic goes here
    // return result
}

Now you can mock your IHWSysManager interface with mock frameworks or you can create a stub class yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download