Mocking Basics
Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies. In mocking, the dependencies are replaced by closely controlled replacement objects that simulate the behavior of the real ones. JustMock creates the replacement objects and manages their lifetime for you.
In the topics of this Getting Started section, you will get familiar with the API of JustMock and will see example scenarios of its basic usage.
Mock the Behavior of a Public Method
To start from the basics, in the first example we will show you how to mock the behavior of a public method for a specific instance. To demonstrate the case, we will use a sample setup representing an order and a warehouse keeping all the inventory for the different orders:
Sample setup
Let’s first verify that the Complete
method of the Order
class properly sets the IsCompleted
property to avoid duplication. Our target method depends on the products currently present in the Products
collection and internally invokes other two methods - HasInventory
and Remove
. To test the code without mocking, you would need to setup a Warehouse
object with a collection keeping the products and maintain that collection during the execution of the different tests. You would have to call the Complete
method using specific arguments for the different cases.
With JustMock, you can directly control the behavior of the methods and ignore the specific data preserved in Warehouse
. Example 1 shows how you can setup the HasInventory
method to always return true
and ignore the logic of Remove
. The demonstrated setup enables you to focus on the logic and ignore the specific data or requirements for the logic to operate.
Example 1: Test IsCompleted marked as expected by controlling the method behavior
Another option that you can use is to create a collection of products and ensure the Products
property uses it instead of messing up the real data.
Example 2: Test IsCompleted marked as expected by controlling the Products property behavior
Next Steps
Now that you know how a simple public class with public members can be tested using JustMock, go ahead and check the next topic of the Getting Started series to learn about the numerous features and scenarios you can easily setup and test. In the Create Mock Instances topic, you will learn how to obtain mocked instances of different implementations.