In this post, i will start with a more traditional mocking example that includes a fund transfer scenario between two different currency account using JustMock.Our target interface that we will be mocking looks similar to:
Moving forward the SUT or class that will be consuming the service and will be invoked by user [provided that the ICurrencyService will be passed in a DI style] looks like:
As, we can see there is a TransferFunds action implemented from IAccountService takes in a source account from where it withdraws some money and a target account to where the transfer takes place using the provided conversion rate.
Our first step is to create the mock. The syntax for creating your instance mocks is pretty much same and is valid for all interfaces, non-sealed/sealed concrete instance classes. You can pass in additional stuffs like whether its an strict mock or not, by default all the mocks in JustMock are loose, you can use it as default valued objects or stubs as well.
Using JustMock, setting up your expectations and asserting them always goes with Mock.Arrang|Assert and this is pretty much same syntax no matter what type of mocking you are doing. Therefore, in the above scenario we want to make sure that the conversion rate always returns 2.20F when converting from GBP to CAD. To do so we need to arrange in the following way:
Here, I have additionally marked the mock call as must. That means it should be invoked anywhere in the code before we do Mock.Assert, we can also assert mocks directly though lamda expressions but the more general Mock.Assert(mocked) will assert only the setups that are marked as "MustBeCalled()”.
Now, coming back to the main topic , as we setup the mock, now its time to act on it. Therefore, first we create our account service class and create our from and to accounts respectively.
Next, we add some money to the GBP account:
Finally, we do our transfer by the following:
Once, everything is completed, we need to make sure that things were as it is we have expected, so its time for assertions.Here, we first do the general assertions:
Following, we do our mock assertion, as have marked the call as “MustBeCalled” it will make sure that our mock is actually invoked. Moreover, we can add filters like how many times our expected mock call has occurred that will be covered in coming posts.
So far, that actually concludes our first mock with JustMock and do stay tuned for more.
Subscribe to be the first to get our expert-written articles and tutorials for developers!