C#模拟IConfiguration不断获取空 [英] c# Mock IConfiguration keeps get null

查看:115
本文介绍了C#模拟IConfiguration不断获取空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问我是否正确模拟了ICo​​nfiguration,因为我一直收到空错误.我正在尝试模拟控制器读取appsettings.json的位置.

May I enquire if I am mocking my IConfiguration correctly as I keep get a null error. I am trying to mock my controller where it reads the appsettings.json.

Controller.cs

 private readonly IConfiguration _configuration;
 public Controller(IConfiguration configuration)
 {
     _configuration = configuration;
 }
 
 public void methodOne() 
 {
      string directory = _configuration.GetValue<string>("section:value");
 }

ControllerTest.cs

public class ControllerTest: ControllerTestsBase<Controller>
{

   public ControllerTest()
   {
      var builder = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json");
      Configuration = builder.Build();
   }

   [Fact]
   public void TestOne()
   {
       Controller.methodOne();
   }
}

当我调试并跟踪到 Controller.cs methodOne 时,_configuration会提示出现空错误.

When I debug and trace to the Controller.cs methodOne, the _configuration keeps prompted null error.

  • 为代码段表示歉意,我再次更新了代码.

推荐答案

嘿,我已经通过创建 IConfiguration

private readonly Controller _controller;

public ControllerTest()
{
    // Create a mock if the IConfiguration object
    Mock<IConfiguration> configuration = new Mock<IConfiguration>();
    // Set it up to return whatever you want it returns back
    configuration.Setup(c => c.GetSection(It.IsAny<string>())).Returns("myDirectoryPath");
    // initialize your controller passing the mock object 
    _controller = new Controller(configuration.Object);
}

类似的东西会起作用.您创建所需的配置的模拟.创建您要测试的控制器的实例,然后将您创建的Mock对象传递到该实例,以便它将获取值.然后,您可以像这样调用测试方法:

something like that would work. You create the mock of the Configuration you need. Create an instance of the controller you want to test, and pass there the Mock object you created, so it will get the values. Then you can call your test method like this:

[Fact]
public void TestOne()
{
    _controller.methodOne();
}

这篇关于C#模拟IConfiguration不断获取空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆