简体   繁体   中英

How do I use NSubstitute to mock ILogger on a constructor

I have the following concrete controller constructor:

public class AuthenticationController : ControllerBase
{
    private readonly IUserRepository<User> _userRepository;
    private readonly ILogger<AuthenticationController> _logger;
    private readonly IConfiguration _config;


    public AuthenticationController(IUserRepository<User> userRepository, ILogger<AuthenticationController> logger, IConfiguration config)
    {
        _userRepository = userRepository;
        _logger = logger;
        _config = config;
    }

I'm trying to mock the constructor, but seem to be having trouble with ILogger.

 var userRepository = Substitute.For<IUserRepository<User>>();
 var config = Substitute.For<IConfiguration>();
 var logger = Substitute.For<ILogger>();

 var controller = new AuthenticationController(userRepository, logger, config);

With logger I've tried the following, but all continue to leave a 'red line' under the Constructor : eg. on the line

var controller = new AuthenticationController(userRepository, logger, config);

AuthenticationController has the red line regardless of what I try.

If I declare logger in the form: var logger = Substitute.For<ILogger<AuthenticationController>>(); the whole right side of = also red lines.

var logger = Substitute.For<ILogger<AuthenticationController>>();

then I've tried:

var auth = Substitute.For<AuthenticationController>();
var logger = Substitute.For<ILogger<auth>>();

When I hover over the red line it mentions that the assembly reference on the api is higher than the unit tests assembly. Both projects target .Net Core 2.1

This is the error generating from my test project:

Assembly 'My.Api' with identity 'My.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'Microsoft.AspNetCore.Mvc.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' which has a higher version than referenced assembly 'Microsoft.AspNetCore.Mvc.Core' with identity 'Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

My test project references my api project. The api project has a reference to Microsoft.AspNetCore.App (2.1.1) My unit test project does not have a direct reference at all to this library.

您需要确保您的代码项目和单元测试项目使用包含ILogger的nuget软件包的相同版本。

Strange, I created a new test project in the solution and still received the same error. So, in my original test project I installed specifically via Nuget the

Microsoft.AspNetCore.Mvc.Core (2.1.1) package

and my error's went away and it run successfully. I have not specifically referenced this in my Api Project. I've put this up in-case others run into a similar issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM