Nsubstitute: Callback not fired for void when Arg.Any passed

Created on 15 Nov 2018  路  2Comments  路  Source: nsubstitute/NSubstitute

Describe the bug
I am using the Fluent Assertions for clear assertions but it doesn't affect this bug.

I have interface with the following method

void ReduceProductAvailability(int productId, int orderedQuantity);

When I create the substitute which throws exception for this

var service = Substitute.For<IProductService>();

service
    .When(e => e.ReduceProductAvailability(Arg.Any<int>(), Arg.Any<int>()))
    .Do(x => throw new NotFoundException("XYZ"));

It not throws when in execution I use

service.ReduceProductAvailability(Arg.Any<int>(), Arg.Any<int>())

but it works if I use simple parameters

service.ReduceProductAvailability(0, 0)

To Reproduce
Compare two of the following tests

  1. This works

    // Arrange
    
    var service = Substitute.For<IProductService>();
    
    service
        .When(e => e.ReduceProductAvailability(Arg.Any<int>(), Arg.Any<int>()))
        .Do(x => throw new NotFoundException("XYZ"));
    
    // Act
    
    Action result = () => service.ReduceProductAvailability(0, 0);
    
    // Assert
    
    result.Should().Throw<NotFoundException>();
    
  2. This not

    // Arrange
    
    var service = Substitute.For<IProductService>();
    
    service
        .When(e => e.ReduceProductAvailability(Arg.Any<int>(), Arg.Any<int>()))
        .Do(x => throw new NotFoundException("XYZ"));
    
    // Act
    
    Action result = () => service.ReduceProductAvailability(Arg.Any<int>(), Arg.Any<int>());
    
    // Assert
    
    result.Should().Throw<NotFoundException>();
    

Expected behaviour
It should throws the exception in both cases

Environment:

  • NSubstitute version: 3.1.0
  • XUnit: 2.4.1
  • FluentAssertions: 5.5.0
  • Platform: dotnetcore2.1 project on Windows

Most helpful comment

Hi,

You're right.
I checked the documentation, but I didn't find this.
Thank you, I will close this issue.

All 2 comments

The second examples do not work because you are using argument matcher in a real call.
See documentation . In general Arg matchers should only be used for mock setup and checking received calls. See also feature request https://github.com/nsubstitute/NSubstitute.Analyzers/issues/35#issue-355796854 for NSubstitute.Analyzers with quick description about the proper usage

Hi,

You're right.
I checked the documentation, but I didn't find this.
Thank you, I will close this issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

surya19876 picture surya19876  路  9Comments

MilesLin picture MilesLin  路  6Comments

semenmiroshnichenko picture semenmiroshnichenko  路  3Comments

mehlian picture mehlian  路  3Comments

p33nty picture p33nty  路  4Comments