Skip to main content
 首页 » 编程设计

c#之单元测试之Controller 未从 ASP.NET Core Web API 项目中的模拟 IConfiguration 中获取值

2024年02月25日31leader

我正在尝试使用模拟服务在 ASP.NET Core Web API 中对我的登录操作进行单元测试,所有模拟工作正常但是当我尝试模拟我的 IConfiguration 文件时, Controller 没有接收到它的值(value)。

这是调用 Controller 操作的单元测试代码:

[Fact] 
public async Task SignInTest() 
{ 
    // Arrange 
    var requestVM = new CustomerSignInRequestVM 
    { 
        EmailPhone = "03026993900", 
        RegNum = "Abc123" 
    }; 
 
    var config = new Mock<IConfiguration>(); 
    //HERE I AM SETTING ALL MY CONFIGURATION VALUES TO RETURN SOME FAKE VALUES 
 
    //config.Setup(cf => cf.GetSection("Jwt:Encryptionkey").Value).Returns("01 02 03");     
    config.Setup(x => x.GetSection("Jwt:Encryptionkey").Value).Returns("abc"); 
    config.Setup(x => x.GetSection("Jwt:Issuer").Value).Returns("test.com"); 
    config.Setup(x => x.GetSection("Jwt:ExpiryTimeInMinutes").Value).Returns("Jwt:ExpiryTimeInMinutes");    
 
    //THIS MOCKING WORK FINE IN CONTROLLER ACTION 
    var customerApplication = new Mock<ICustomerApplication>(); 
    customerApplication.Setup(app => app.GetCustomer(It.IsAny<SignIn>())).ReturnsAsync(GetCustomerMockData); 
 
    var claimApplication = new Mock<IClaimApplication>(); 
    claimApplication.Setup(app => app.GetListByRole(It.IsAny<ApplicationRole>())).ReturnsAsync(new List<ApplicationClaim> { new ApplicationClaim { Active = true, ClaimCode = "AUC_GA", ClaimLabel = "Auction.GetAll" } }); 
 
    //I'm also injecting my IConfiguration object here in my controller setup 
 
    var controller = new CustomerController(customerApplication.Object, null, claimApplication.Object, null, null, config.Object, null); 
 
    // Act 
    var response = await controller.SignIn(requestVM, new CancellationToken()); 
    var okObjectResult = response as OkObjectResult; 
 
    // Assert 
    Assert.Equal(200, okObjectResult.StatusCode); 
} 

但是当我尝试从我的 Controller 操作中的 injected IConfiguration 服务中检索值时,如下所示:

var Issuer = Configuration["Jwt:Issuer"],

这向我返回了 null,我不确定我在这里做错了什么。

请您参考如下方法:

您设置了 x.GetSection("Jwt:Issuer").Value 但调用了 Configuration["Jwt:Issuer"]。这是两件不同的事情,将导致上述问题。

与尝试正确模拟所有内容相比,您最好构建一个具有所有所需功能的内存配置。

//... 
 
var fakeValues = new Dictionary<string, string> 
{ 
    {"Jwt:Encryptionkey", "abc"}, 
    {"Jwt:Issuer", "test.com"}, 
    {"Jwt:ExpiryTimeInMinutes", "some value"} 
}; 
 
IConfiguration config = new ConfigurationBuilder() 
    .AddInMemoryCollection(fakeValues) 
    .Build(); 
 
//... 
 
var controller = new CustomerController(customerApplication.Object, null,  
        claimApplication.Object, null, null, config, null); 
 
//... 

引用 Configuration in ASP.NET Core