Unit Testing Private Methods in C#

How do you unit test private methods?

If you are using .net, you should use the InternalsVisibleToAttribute.

Unit Test c# for Private Method

You need to instantiate the Order argument of CheckWarehouseAvailability and pass it as an argument to PrivateObject.Invoke():

var order = new Order(); 
var retVal = privBase.Invoke("CheckWarehouseAvailability", order);
// ... Assert

MSDN: PrivateObject.Invoke(String, Object[])

Also, I'm not sure what you are asserting here:

Assert.AreEqual(true, retVal);

...as CheckWarehouseAvailability has it's return type set to void, not bool.

How to unit test a private static/shared method?

You could use PrivateType and InvokeStatic for this:

    Dim foo = New PrivateType(GetType(TestClass))
foo.InvokeStatic("SampleSharedMethod", {arg1})

If you want to pass parameters ByRef - for instance if the method under test looked something like this:

    Private Shared Sub SampleSharedMethod(ByRef arg As String)
arg += "abc"
End Sub

You can use this overload of InvokeStatic to get the results back:

    Dim foo = New PrivateType(GetType(TestClass))
Dim params() As Object = {"123"}
foo.InvokeStatic("SampleSharedMethod", params)

Dim updatedValue = params(0) ' This would be 123abc in this example

.Net core library: How to test private methods using xUnit

A quick solution is to make private members that you want to test internal.

You can then add an InternalsVisibleTo attribute to your main library's AssemblyInfo.cs. This will allow your test library (and no other library, without reflection) access to the internal methods/classes in your main library.

e.g.

[assembly: InternalsVisibleTo("Library.Tests")]


Related Topics



Leave a reply



Submit