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
Creating Wizards For Windows Forms in C#
Dpi Awareness - Unaware in One Release, System Aware in the Other
Entity Framework 5 Updating a Record
Raw SQL Query Without Dbset - Entity Framework Core
How to Reflect Over the Members of Dynamic Object
How to Specify a Path in an Attribute to Map a Property in My Class to a Child Property in My Json
C# Catch a Stack Overflow Exception
Unity: Null While Making New Class Instance
Setting Authorization Header of Httpclient
How to Save/Restore Serializable Object To/From File
How Expensive Are Exceptions in C#
Why Must "Stride" in the System.Drawing.Bitmap Constructor Be a Multiple of 4
Client to Send Soap Request and Receive Response
Is There Any Significant Difference Between Using If/Else and Switch-Case in C#
I Want to Find the Maximum Frequency of a Common Digit in a Consecutive Subset of Integer Array