-2

I used following code to test the private method after seeing another solution but this is not working. Compile Error.

FooClass target = new FooClass(DBContext, null, null, null, null) 
PrivateObject privObj = new PrivateObject(target);
var actual = privObj.Invoke("privateFoo", fooParam); 

private method receives one parameter of object. Parameter Object is used earlier and used for testing in other methods too. So I'm confident about it. And private method does not use any null objects I'm passing either. No dependencies. Want to know if there's another way to unit test private methods or I'm missing something.

Pramuka
  • 1,064
  • 1
  • 8
  • 15
  • 2
    Can you elaborate on how your code "doesn't work". What were you expecting, and what actually happened? If you got an exception, post the line it occurred on and the exception details. – gunr2171 Jun 19 '14 at 14:29
  • 2
    Are you using a unit-testing framework of some kind? Generally speaking, there are better ways to test your code than using reflection on private methods. Why not test the public methods that use the private ones? http://stackoverflow.com/questions/9122708/unit-testing-private-methods-in-c-sharp – xDaevax Jun 19 '14 at 14:34
  • possible duplicate of [How do you unit test private methods?](http://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods) – Daniel Mann Jun 19 '14 at 15:19
  • possible duplicate of [When is it appropriate to bypass encapsulation in unit tests?](http://stackoverflow.com/questions/23702784/when-is-it-appropriate-to-bypass-encapsulation-in-unit-tests) – Jeroen Vannevel Jun 20 '14 at 10:05

2 Answers2

2

As others have said, you should not unit test private methods. You want to test only public methods, because public methods represent your class's visible API. Private methods are implementation details.

Let's say you have a method like this:

public IEnumerable<Foo> GetValidCustomers() 
{
    var customers = _database.GetCustomers();
    return this.FilterToValidCustomers(customers);
}
private IEnumerable<Foo> FilterToValidCustomers(IEnumerable<Foo> customers) 
{
    //crazy complex logic here 
}

In this example, you'd want to test that you get the correct set of valid customers. The logic it uses to filter the customer list is irrelevant, as long as you're getting the data you expect.

If you have very complex logic in your private methods that you're having trouble fully testing via your class's public API, that indicates a design problem with your class -- the class is probably too complicated. You should deconstruct your complex class into multiple smaller classes, then test them normally through their public APIs.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
0

You should not test not public methods, anyway you could make protected internal your private method, then mark InternalsVisibleToAttribute your library, so that you can access protected internal methods by your tests

ale
  • 10,012
  • 5
  • 40
  • 49