How can I check if an anonymous function has been called with NSubstitute?

How can I check if an anonymous function has been called with NSubstitute?

By : Qu Ziyuan
Date : November 15 2020, 06:54 AM
seems to work fine I want to check if an anonymous function has been called with NSubstitute. A method in a class I have takes a Func<> parameter, and I want to make sure this parameter is called (or not called). I have tried the following, but it does not seem to work: , Try replacing
code :

Share : facebook icon twitter icon
Function is called when I do not expect it to with NSubstitute

Function is called when I do not expect it to with NSubstitute

By : Gintaras
Date : March 29 2020, 07:55 AM
seems to work fine This is a side-effect of how NSubstitute works: to get that particular syntax it needs to actually call the method to get a reference to that method.
Moq and others use lambdas and can pick the particular method out from there, without the need to run the method itself. (This means NSubstitute also fails to detect or throw on non-virtual method calls.)
Nsubstitute check if setter has been called

Nsubstitute check if setter has been called

By : Johnny
Date : March 29 2020, 07:55 AM
To fix the issue you can do The standard way to test this is to just read the value back out of the property:
code :
Assert.AreEqual(filterable.Filter, filter);
filterable.Received().Filter = filter;
How to check any of multiple overloads called NSubstitute

How to check any of multiple overloads called NSubstitute

By : user1818271
Date : March 29 2020, 07:55 AM
may help you . NSubstitute does not have built-in syntax for this, but it is possible to query all ReceivedCalls() and manually assert on this.
For example:
code :
var errorCalls = logger.ReceivedCalls()
    .Where(x => x.GetMethodInfo().Name == nameof(logger.Error))
    .Where(x => (x.GetArguments()[0] as string).ToLower().Contains("email"));

Assert.AreEqual(1, errorCalls.Count());
Why isn't NSubstitute.Return called?

Why isn't NSubstitute.Return called?

By : SkyDelegate
Date : March 29 2020, 07:55 AM
wish helps you There does not seem any obvious problem with the example code, so I am guessing it is an issue with some of the code not shown. Is it possible to post a runnable version that illustrates the problem? I also suggest adding NSubstitute.Analyzers to your project as it can help detect issues that sometimes causing confusing test behaviour.
Here's a simplified version that demonstrates everything working correctly. If it is possible to modify this to reproduce the problem that would be really helpful!
code :
public interface IRepository {
    ValueForEntity GetValueForEntity(int v);
    void InsertValueForEntity(int v, ValueForEntity valueForEntity);

public class RealRepository : IRepository {
    private readonly IDictionary<int, ValueForEntity> data = new Dictionary<int, ValueForEntity>();
    public ValueForEntity GetValueForEntity(int v) => data[v];
    public void InsertValueForEntity(int v, ValueForEntity valueForEntity) => data[v] = valueForEntity;           

public class ValueForEntity {
    public int Id { get; set; }
public class EntityFactory {
    private readonly IRepository repo;
    public EntityFactory(IRepository repo) => this.repo = repo;
    public ValueForEntity CreateEntity(int id) {
        repo.InsertValueForEntity(id, new ValueForEntity { Id = id });
        return repo.GetValueForEntity(id);
public void Example() {
    var realRepository = new RealRepository();
    var proxyRepository = Substitute.For<IRepository>();

        .When(repo => repo.InsertValueForEntity(Arg.Any<int>(), Arg.Any<ValueForEntity>()))
        .Do(callInfo => realRepository
            .InsertValueForEntity((int)callInfo.Args()[0], (ValueForEntity)callInfo.Args()[1]));

        .Returns(callInfo => realRepository

    var factory = new EntityFactory(proxyRepository);
    var entity = factory.CreateEntity(42 /* args */); 

    proxyRepository.Received().InsertValueForEntity(entity.Id, Arg.Any<ValueForEntity>());
    Assert.Equal(42, entity.Id);
How to check properly that ILogger.LogCritical has been called with NSubstitute?

How to check properly that ILogger.LogCritical has been called with NSubstitute?

By : user3489505
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have some hard times with NSubstitute to check whether the method ILogger.LogCritical(...) has been called. , I ended up using Moq for that particular kind of tests:
code :
// Defining an extension method
public static void IsLogReceived(this IMock<ILogger<StockService>>logger, LogLevel level, int count = 1) =>
    logger.Verify(x =>
            (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), 

// [...]

// and using the ext. method like that:
public void TestNSubstituteAgain()
    var loggerMock = new Mock<ILogger<StockService>>();
    var logger = loggerMock.Object;
    logger.LogCritical(new Exception(), "Hey lads!");

Related Posts Related Posts :
  • Why does C# also not allow empty conditions in while loops?
  • Unable to get a block of code into my regex match groups
  • What is difference between dbcontext.Add and dbcontext.AddObject
  • How do I update the file version number of C# DLL without recompiling?
  • Value for html control always null
  • HttpClient hangs when timeout is setting (Windows Phone)
  • Handle Multiple Form tag in asp.net page?
  • create word document with html content in c#
  • Confusion about Find And Replace
  • Format sms messages in Clickatell
  • Automated Function Overload
  • String to date in MS Access SQL statement gives type mismatch error
  • ShowDialog exiting on certain events
  • Is there a try Convert.ToInt32... avoiding exceptions
  • How to move wpf application into minimize tray at Window Start-up C#?
  • How to change display format of long variable?
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org