How to mock a method that is called multiple times in single call using Moq in C#.NET?

Bijay Yadav

I am trying to mock the below method but the updateRefundReqeust returns null instead updated record.

public async Task<bool> InvokeAsync(Batch batch)
{
        var refundRequests = await this.RefundRequestRepository.GetsAsync(batch.RefundRequests.Select(x => x.Id));

        foreach (var getRefundRequest in refundRequests)
        {
            getRefundRequest.Status = RefundRequestStatus.Closed;
            getRefundRequest.LastUpdatedBy = "Test User";

            RefundRequest updateRefundReqeust = await UpdateRefund.InvokeAsync(getRefundRequest);
           //Returns null instead of updated record
        }
}

Unit test and Mocking method

[Fact]
public async Task Post_Batch()
{
    var refundRequests = await this.RefundRequestRepository.GetsAsync(batch.RefundRequests.Select(x => x.Id));

    foreach (var getRefundRequest in refundRequests)
    {
        this.MockUpdateRefund
        .Setup(x => x.InvokeAsync(getRefundRequest))
        .Returns(async () =>
        {
            getRefundRequest.Status = RefundRequestStatus.Closed;
            getRefundRequest.LastUpdatedBy = Factory.RefundRequest.TestUserName;
            return await Task.Run(() => getRefundRequest);
        });
    }

    var postRefund = await PostBatch.InvokeAsync(batch);

    //Assert
    postRefund.ShouldNotBeNull();
    postRefund.IsPosted.ShouldBeTrue();
}

Is something missed in the Mocking? Please let me know if more stuffs are required to support the question.

StuartLC

Here's a couple of points:

  • You don't need to setup a Mock multiple times, if all the Mocked calls are to return the same value. One Setup will service all calls with the given result.

  • If you want the mocked dependency to return different canned values on each call, then use SetupSequence and then chain as many Returns / ReturnsAsync for each result. However, it looks like you need to intercept the parameter and mutate it, and return it - there are Returns overloads which capture the parameter.

  • For async methods, you'll want to use ReturnsAsync instead of Returns. Both of these have overloads allowing you to capture the passed parameter to the mocked method.

  • You probably don't want the overhead of a new thread with Task.Run. Task.FromResult will return you a task wrapping the result.

  • You typically won't want to Setup on a reference type unless you know for sure that the same reference instance will be passed to the dependency, since if any other instance is passed, the Mock will be ignored. It.Is/IsAny can be used as wildcards.

I believe you want something along the lines of:

this.MockUpdateRefund
    .Setup(x => x.InvokeAsync(It.IsAny<RefundRequest>()))
    .ReturnsAsync<RefundRequest>((RefundRequest getRefundRequest) =>
    {
        getRefundRequest.Status = RefundRequestStatus.Closed;
        getRefundRequest.LastUpdatedBy = Factory.RefundRequest.TestUserName;
        return Task.FromResult(getRefundRequest);
    });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

how to mock a method call using moq

From Dev

Mock an Interface and call the original method of Implementation using MOQ and C#

From Java

Python Mock object with method called multiple times

From Dev

Is a call needed to Setup a method on Mock object that we want to Verify that it is called using Moq?

From Dev

How to verfiy that a method has been called a certain number of times using Moq?

From Dev

Count number of times a recursive method is called using Moq

From Dev

Mock a call to IQueryable using moq

From Dev

How to call a method multiple times in parallel using CompletableFuture in Spring Boot

From Dev

How to verify a method which was called multiple times

From Dev

How do I mock nested service call using moq

From Dev

How to mock a service call with a lambda expression using Moq

From Dev

How can I dispatch same method to be called multiple times and give call order number as parameter in WPF app?

From

Using Moq to determine if a method is called

From Dev

How can I mock a simple method using Moq framework?

From Dev

How to mock out the server transfer method using shims and or Moq

From Dev

Using Moq, How do you Mock a method that uses local variables

From Dev

How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

From Dev

C# Mock using Moq

From

How to verify that method was NOT called in Moq?

From Dev

How to call a method multiple times to change a variable?

From Dev

Using ng-class with a function call - called multiple times

From

Verify a method call using Moq

From Dev

How to mock a method which is called by another method using EasyMock?

From Java

How to mock one method with different parameters multiple times?

From Dev

Compute method is called multiple times?

From Dev

How to mock static method calls from multiple classes in a single try block using Mockito?

From Dev

Mock certain part of the method using Moq

From Dev

Mock Async method on Service using Moq

From

Using Moq to mock an asynchronous method for a unit test

Related Related

  1. 1

    how to mock a method call using moq

  2. 2

    Mock an Interface and call the original method of Implementation using MOQ and C#

  3. 3

    Python Mock object with method called multiple times

  4. 4

    Is a call needed to Setup a method on Mock object that we want to Verify that it is called using Moq?

  5. 5

    How to verfiy that a method has been called a certain number of times using Moq?

  6. 6

    Count number of times a recursive method is called using Moq

  7. 7

    Mock a call to IQueryable using moq

  8. 8

    How to call a method multiple times in parallel using CompletableFuture in Spring Boot

  9. 9

    How to verify a method which was called multiple times

  10. 10

    How do I mock nested service call using moq

  11. 11

    How to mock a service call with a lambda expression using Moq

  12. 12

    How can I dispatch same method to be called multiple times and give call order number as parameter in WPF app?

  13. 13

    Using Moq to determine if a method is called

  14. 14

    How can I mock a simple method using Moq framework?

  15. 15

    How to mock out the server transfer method using shims and or Moq

  16. 16

    Using Moq, How do you Mock a method that uses local variables

  17. 17

    How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

  18. 18

    C# Mock using Moq

  19. 19

    How to verify that method was NOT called in Moq?

  20. 20

    How to call a method multiple times to change a variable?

  21. 21

    Using ng-class with a function call - called multiple times

  22. 22

    Verify a method call using Moq

  23. 23

    How to mock a method which is called by another method using EasyMock?

  24. 24

    How to mock one method with different parameters multiple times?

  25. 25

    Compute method is called multiple times?

  26. 26

    How to mock static method calls from multiple classes in a single try block using Mockito?

  27. 27

    Mock certain part of the method using Moq

  28. 28

    Mock Async method on Service using Moq

  29. 29

    Using Moq to mock an asynchronous method for a unit test

HotTag

Archive