Mock Non-Public API
The non-public API like the private members are essential parts of the implementation of each system. A developer won’t be able to fully control the behavior of all the classes or dependencies that they might need to if they are unable to mock the private implementations.
To provide you with full control on the behavior of the different private implementations, JustMock exposes the Mock.NonPublic
option. With this option, you can arrange the expectations and behavior for private and internal members.
To illustrate its usage, we will be using the following sample setup that takes care of gifts distribution for orders containing more than 5 products:
Sample setup
With the implementation above, testing that the gifts distribution is correctly performed without using mocks would require us to investigate the implementation of the IsEligibleForGift
method and setup our order in a way that ensures the method will return true
. With JustMock you can skip these details and just define the value you need to be returned so that the execution of the logic can continue in the desired way.
Example 1: Arrange private field
With Mock.NonPublic
you can use the same familiar approach for arranging the getter and setter of properties and the behavior of methods that have restrictive access modifier.
Calling Private Methods and Properties
JustMock gives you the ability to easily invoke private members from your tests as well. To achieve that, you will need to use the PrivateAccessor
class. It represents a wrapper for objects that allows you invoke their private or internal members without using complex queries to select them. While PrivateAccessor
uses the .NET Reflection API internally, it exposes convenient and easy to read methods that hide the complexity of the reflection in a single line of code.
To see PrivateAccessor
in action, let’s say that we would like to test that invoking the Complete
method from our sample setup doesn’t add gifts to orders that are already processed. An order is considered processed when its isCompleted
field is set to true
. There is also a method changing the status and we can use it to avoid additional unneeded processing.
Example 2: Call a private method and obtain the value of a private field
Next Steps
The Mock System API topic will provide you with more details on how you can arrange members defined inside the .NET.