Timigen
Timigen

Reputation: 1025

PrivateObject Invoke throwing MissingMethodException

I have the following code, in a unit test in Visual Studio 2012. I am trying to test a private method the GatherData method is in the ExcelFile class. However When I run the test I am getting a MissingMethodException. How can I invoke a private method in a class so I can unit test?

ExcelFile xFile = new ExcelFile("pathhere");
PrivateObject po = new PrivateObject(xFile);

var retVal = po.Invoke("GatherData");

Here is some of the ExcelFile class:

public class ExcelFile
{

    private FileInfo excelFileInfo;
    private ExcelWorksheet workSheet;

    private Dictionary<string, string> data = new Dictionary<string, string>();

    public ExcelFile(string path)
    {
        this.excelFileInfo = new FileInfo(path);

    }

    private Dictionary<string, string> GatherData(ExcelWorksheet workSheet)
    {
        Dictionary<string, string> data = new Dictionary<string, string>();

        int endDataRow = workSheet.Dimension.Rows;

        for (int rowNumber = 2; rowNumber <= endDataRow; rowNumber++)
        {
            if (ValidateRow(rowNumber))
            {
                string columnOneValue = workSheet.Cells[rowNumber, 1].Value.ToString().Trim(),
                       columnTwoValue = workSheet.Cells[rowNumber, 2].Value.ToString().Trim();

                data.Add(columnOneValue, columnTwoValue);
            }
        }
        return data;
    }   
}

Upvotes: 1

Views: 3506

Answers (2)

Takahashinator
Takahashinator

Reputation: 189

The method GatherData requires an argument of type ExcelWorksheet in order to work. If you create an object of ExcelWorksheet and then use the code:

ExcelFile xFile = new ExcelFile("pathhere");
PrivateObject po = new PrivateObject(xFile);

var retVal = po.Invoke("GatherData", new object[] {excelWorksheetObject});

It should work for you.

Check out this post for more details: Running into System.MissingMethodException: Method Not Found with PrivateObject

Cheers!

Upvotes: 7

invernomuto
invernomuto

Reputation: 10211

Usually you should not test private methods of classes, but only the public interface, then using any sort of reflection for this purpose, in my opinion, is completely the wrong approach, anyway in .NET there is a system to test protected internal methods with InternalsVisibleToAttribute, decorate your under test class with

[assembly:InternalsVisibleTo("YourTestClass")]

so you dont break the encapsulation

Upvotes: 1

Related Questions