Nsubstitute How to mock private method called by method being tested

I want to create a unit test far a method that looks like this

public async Task<Country> Get(string slug)
{
   var entityId = GetCountryEntityId(string slug);
   ... Do stuff
}

Which calls this private method

private string GetCountryEntityId(string slug)
{
    var properties = new EntityProperties(slug, CacheHandlerKeys.Countries, "allCountries");
    var entityId = _entityIdService.GetEntityId(properties);

    if (string.IsNullOrEmpty(entityId))
    {
        var e = new NullEntityIdException(slug);
        e.Data.Add("Slug", slug);
        throw e;
    }

    return entityId;
}

Which checks the cache “allCountries” for an item matching “slug” existing inside the substituted memory cache

I have added these lines in my test before calling the method I am attempting to test.

var props = new EntityProperties(slug, CacheHandlerKeys.Countries, "allCountries");
_entityIdService.GetEntityId(props).Returns("Test");

Where _entityIdService is a substitute.
Followed by the call to the method

var result = await repo.Get(slug);

I can see whilst debugging that when the private method is called it is accessing my substituted version of IEntityIdService, using an exact match to my “props” variable, but it’s still returning a blank string instead of the text “Test”.

How do I get it to return the text “Test”?

Success. This is the code that gives me what I wanted.

_entityIdService.GetEntityId(Arg.Any<EntityProperties>()).ReturnsForAnyArgs(x => "Test");

var result = await repo.Get(slug);

This returns the text “Test” when called by the tested method.

The key is in the arguments passed to the method “GetEntityId”, instead of passing an explicit EntityProperties implementation – which I was trying to do originally, I am now giving it the inbuilt Arg.Any argument.

Obvious when you know how.

Leave a Comment