<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Audrius Masiulionis</title>
    <description>The latest articles on DEV Community by Audrius Masiulionis (@audmasiulionis).</description>
    <link>https://dev.to/audmasiulionis</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F766615%2Ff671fd8a-45e7-4c15-973c-3747612de089.jpg</url>
      <title>DEV Community: Audrius Masiulionis</title>
      <link>https://dev.to/audmasiulionis</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/audmasiulionis"/>
    <language>en</language>
    <item>
      <title>A better way to verify Mocks (XUnit, Moq, .NET) </title>
      <dc:creator>Audrius Masiulionis</dc:creator>
      <pubDate>Sun, 13 Feb 2022 09:55:55 +0000</pubDate>
      <link>https://dev.to/audmasiulionis/a-better-way-to-verify-mocks-xunit-moq-net-imp</link>
      <guid>https://dev.to/audmasiulionis/a-better-way-to-verify-mocks-xunit-moq-net-imp</guid>
      <description>&lt;p&gt;When I started practicing TDD writing unit tests became my everyday routine. Over my professional career, I've picked up a few techniques that help write tests more cleanly and verify all of the code dependencies. I use XUnit test framework for writing tests and Moq Nuget package to mock code dependencies. I've noticed that most developers are not familiar with good mock verification techniques, which I will cover in this post.&lt;/p&gt;

&lt;p&gt;In this post, I will not cover the benefits of unit testing like better code quality, executable documentation, or ease of executing complex business scenarios swiftly. I find unit testing in most cases beneficial and even mandatory.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sample Code
&lt;/h2&gt;

&lt;p&gt;To start unit testing some code is needed. I've created a simple class with a single method. Class's method contains logic to create a new order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OrderService
{
    private readonly IItemRepository _itemRepository;
    private readonly IOrderRepository _orderRepository;

    public OrderService(
        IItemRepository itemRepository, 
        IOrderRepository orderRepository)
    {
        _itemRepository = itemRepository;
        _orderRepository = orderRepository;
    }

    public async Task CreateAsync(int itemId, int itemQuantity)
    {
        var item = await _itemRepository.GetAsync(itemId);
        if (item.Stock &amp;lt; itemQuantity) 
            throw new Exception($"Item id=[{itemId}] has not enough stock for order.");

        Order order = new()
        {
            ItemId = item.Id,
            Quantity = itemQuantity
        };

        await _orderRepository.CreateAsync(order);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's assume that this retrieves data from a database. Those dependencies are abstracted in repositories. Abstracted dependencies are mandatory for mocking in unit testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing the code
&lt;/h2&gt;

&lt;p&gt;I like to start with a happy path unit test. But first, let's begin with some test boilerplate code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OrderServiceTests
{
    private readonly OrderService _sut;
    private readonly Mock&amp;lt;IItemRepository&amp;gt; _itemRepositoryMock;
    private readonly Mock&amp;lt;IOrderRepository&amp;gt; _orderRepositoryMock;

    public OrderServiceTests()
    {
        _itemRepositoryMock = new Mock&amp;lt;IItemRepository&amp;gt;();
        _orderRepositoryMock = new Mock&amp;lt;IOrderRepository&amp;gt;();
        _sut = new OrderService(
            _itemRepositoryMock.Object, 
            _orderRepositoryMock.Object);
    }

    [Fact]
    public void CreateAsync_ShouldCreateNewOrder()
    {
        Assert.False(true);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the code is building successfully and we are getting a failed test result we are all set. The next step is to implement the happy path unit test.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Fact]
    public async Task CreateAsync_ShouldCreateNewOrder()
    {
        const int itemId = 1;
        const int quantity = 2;
        const int existingItemStock = 3;

        _itemRepositoryMock.Setup(m =&amp;gt; m.GetAsync(It.Is&amp;lt;int&amp;gt;(i =&amp;gt; i == itemId)))
            .ReturnsAsync(() =&amp;gt; new Item
            {
                Id = itemId,
                Stock = existingItemStock
            });

        await _sut.CreateAsync(itemId, quantity);

        _itemRepositoryMock.Verify(m =&amp;gt; m.GetAsync(itemId));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break down this test. I am using AAA(&lt;strong&gt;A&lt;/strong&gt;rrange, &lt;strong&gt;A&lt;/strong&gt;ct, &lt;strong&gt;A&lt;/strong&gt;ssert) pattern for all my unit tests. This is an industry-standard and is a clean way to structure tests.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In the "arrange" part we specify what parameters are being used and set up the mock's method result after call.&lt;/li&gt;
&lt;li&gt;In the "act" part we call the method that is being tested.&lt;/li&gt;
&lt;li&gt;In the "assert" part mock calls are verified that has been set up. I am not using Asserts because my method doesn't return a value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Although this test passed, it has a problem. I didn't verify if &lt;code&gt;await _orderRepository.CreateAsync(order);&lt;/code&gt;. And I didn't setup &lt;code&gt;_orderRepositry&lt;/code&gt; mock. This is caused by Moq default mock behavior. When you create a mock the behavior is set to Default. How this is performed can be viewed in Moq's source code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
///   Initializes an instance of the mock with &amp;lt;see cref="MockBehavior.Default"/&amp;gt; behavior.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;example&amp;gt;
///   &amp;lt;code&amp;gt;
///     var mock = new Mock&amp;lt;IFormatProvider&amp;gt;;();
///   &amp;lt;/code&amp;gt;
/// &amp;lt;/example&amp;gt;
public Mock(): this(MockBehavior.Default)
{
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;MockBehavior&lt;/code&gt; is an enum that specifies your created mocks behavior. Available values and behaviors are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;Strict&lt;/em&gt;: an exception is thrown whenever a method or property is invoked without matching configuration.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Loose&lt;/em&gt;: Moq accepts all invocations and attempts to create a valid return value.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Default&lt;/em&gt;: same as &lt;em&gt;Loose&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By default Moq allows to create unit tests without forcing declaring every expected call. This can speed up test development, but I believe this is a bad practice. Developers must own responsibility for their code and every change they make to the code. This can be ensured by setting &lt;code&gt;MockBehavior&lt;/code&gt; strict. This will require to set mock invocations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public OrderServiceTests()
    {
        _itemRepositoryMock = new Mock&amp;lt;IItemRepository&amp;gt;(MockBehavior.Strict);
        _orderRepositoryMock = new Mock&amp;lt;IOrderRepository&amp;gt;(MockBehavior.Strict);
        _sut = new OrderService(_itemRepositoryMock.Object, _orderRepositoryMock.Object);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If mock invocation isn't set up exception is trhowned with following message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Moq.MockException
IOrderRepository.CreateAsync(Order) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To fix the test we need to add the setup for &lt;code&gt;IOrderRepository&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Fact]
    public async Task CreateAsync_ShouldCreateNewOrder()
    {
        const int itemId = 1;
        const int quantity = 2;
        const int existingItemStock = 3;

        _itemRepositoryMock.Setup(m =&amp;gt; m.GetAsync(It.Is&amp;lt;int&amp;gt;(i =&amp;gt; i == itemId)))
            .ReturnsAsync(() =&amp;gt; new Item
            {
                Id = itemId,
                Stock = existingItemStock
            });

        _orderRepositoryMock.Setup(m =&amp;gt; m.CreateAsync(It.IsAny&amp;lt;Order&amp;gt;())).Returns(Task.CompletedTask);

        await _sut.CreateAsync(itemId, quantity);

        _itemRepositoryMock.Verify(m =&amp;gt; m.GetAsync(itemId));
        _orderRepositoryMock.Verify(m =&amp;gt; m.CreateAsync(It.IsAny&amp;lt;Order&amp;gt;()));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After these fixes you can see that we are introducing more verification code. If you have multiple setups all the verifications must be performed. If your code is more complex and has multiple method calls this introduces complexity and trivial code which can be avoided. This can be achieved with &lt;code&gt;MockRepository&lt;/code&gt; class which is helps mock instance creation and management. This class helps to create and verify mocks in one place.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OrderServiceTests
{
    private readonly OrderService _sut;
    private readonly MockRepository _mockRepository;
    private readonly Mock&amp;lt;IItemRepository&amp;gt; _itemRepositoryMock;
    private readonly Mock&amp;lt;IOrderRepository&amp;gt; _orderRepositoryMock;

    public OrderServiceTests()
    {
        _mockRepository = new MockRepository(MockBehavior.Strict);
        _itemRepositoryMock = _mockRepository.Create&amp;lt;IItemRepository&amp;gt;();
        _orderRepositoryMock = _mockRepository.Create&amp;lt;IOrderRepository&amp;gt;();
        _sut = new OrderService(_itemRepositoryMock.Object, _orderRepositoryMock.Object);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using MockRepository we set same mock behavior and we can verify all calls using &lt;code&gt;VerifyAll()&lt;/code&gt; method;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; [Fact]
    public async Task CreateAsync_ShouldCreateNewOrder()
    {
        //test code

        //_itemRepositoryMock.Verify(m =&amp;gt; m.GetAsync(itemId));
        //_orderRepositoryMock.Verify(m =&amp;gt; m.CreateAsync(It.IsAny&amp;lt;Order&amp;gt;()));
        _mockRepository.VerifyAll();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To take a step further we can use &lt;code&gt;Dispose()&lt;/code&gt; method to verify mocks. &lt;code&gt;Dispose()&lt;/code&gt; using XUnit runs after each test, so we can verify all mocks that have been setup and avoid &lt;code&gt;_mockRepository.VerifyAll()&lt;/code&gt; code line in each test method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OrderServiceTests : IDisposable
{
    private readonly OrderService _sut;
    private readonly MockRepository _mockRepository;
    private readonly Mock&amp;lt;IItemRepository&amp;gt; _itemRepositoryMock;
    private readonly Mock&amp;lt;IOrderRepository&amp;gt; _orderRepositoryMock;

    public OrderServiceTests(){...}

    [Fact]
    public async Task CreateAsync_ShouldCreateNewOrder(){...}

    public void Dispose()
    {
        _mockRepository.VerifyAll();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way we have a neat way to verify mocks and keep the test code cleaner.&lt;/p&gt;

&lt;p&gt;Full code can be found &lt;a href="https://github.com/AudMasiulionis/mock-factory-example"&gt;here&lt;/a&gt;.&lt;br&gt;
More on Moq can be found &lt;a href="https://github.com/moq/moq4"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>testing</category>
      <category>dotnet</category>
      <category>unittesting</category>
    </item>
  </channel>
</rss>
