views:

85

answers:

2

I am trying to write a unit test for a method, which has a call to method from dll. Is there anyway i can mock the dll methods so that i can unit test?

public string GetName(dllobject, int id)
{
     var eligibileEmp = dllobject.GetEligibleEmp(id); <---------trying to mock 
                                                                 this method

     if(eligibleEmp.Equals(empValue)
     {
      ..........
     }
}
+1  A: 

When using a third party library that doesn't provide a means of test doubling for unit testing, the best resort is to create a test doublable Facade. Create a class whose sole responsibility is to provide a test doublable interface into the third party libary. It does nothing but pass calls to the library, but it does it such that you can bind against an abstraction of it and mock it.

For example:

public interface IMyDllObject
{
   object DllObject {get; set;}
   object GetEligibleEmp(int id);
}

public class MyDllObject : IMyDllObject
{
   object DllObject {get; set;}
   object GetEligibleEmp(int id)
   {
       DllObject.GetEligibleEmp(id);
   }
}

// elsewhere in your code:
IMyDllObject myDllObject = CreateMyDllObject(); // factory method, can return test double
// elsewhere elsewhere
var eligibleEmp = myDllObject.GetEligibleEmp(id);

That said, do not do this for every function/class/method in the library! It's probably not necessary. Only double the things that rely on external resources you cannot control in a unit test like files or network communcication.

Randolpho
+1  A: 

If the method you're trying to stub is virtual, then you should be able to stub is, but if not then you're best bet is to make a wrapper around it that you can stub.

Example:

internal class EmployeeWrapper
{
    RealEmployeeFactory EmployeeFactory {get; set;}

    public virtual RealEmployee GetEligibleEmp(int id)
    {
        return EmployeeFactory.GetEligibleEmp(id);
    }
} 

I'm just guessing at your class structure because you don't have it in your question but I think you get the idea.

Then you would change your method like this:

public string GetName(EmployeeWrapper employee, int id)
{
     var eligibileEmp = employee.GetEligibleEmp(id); <---------you can stub this

     if(eligibleEmp.Equals(empValue)
     {
      ..........
     }
}
Joseph