C# xUnit 依赖注入

问题描述 投票:0回答:1

我目前正在开发一个依赖依赖注入的项目。我想为它创建一个测试。如何模拟服务并将其传递给测试对象?

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<CustomService>(new (CustomService("Param")));

var app = builder.Build();

ClassToTest.cs

public Class ClassToTest
{
    [Inject]
    protected CustomService _customService { get; set; }

    public ClassToTest(string args)
    {
        // ...
    }
 
    public void MethodToTest()
    {
         var restult = CustomService.Get()
    }
}

CustomService.cs

// .
// .
public string Get()
{
    return "Hello World"
}
c# xunit .net-8.0
1个回答
0
投票

这是我解决问题的方法。

我最终使用了@Julians 和@Daniel Manns 方法的组合。

ClassToTest.cs

  protected ICustomService _customService { get; set; }

    public ClassToTest(string args, ICustomService cs)
    {
        _customService = cs;
        // ...
    }

测试.cs

 [Fact]
 var cs = new CustomService()
 var SUT = new ClassToTest("args", cs)
 // ...
© www.soinside.com 2019 - 2024. All rights reserved.