如何使用 XUnit 编写一个简单的测试用例?

How to write a simple testing case using XUnit?

完全不熟悉测试,我有一个这样的控制器:

public class CheckRegController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly AppSettings _appSettings;

    public CheckRegController(ApplicationDbContext context, IOptions<AppSettings> appSettings)
    {
        _context = context;
        _appSettings = appSettings.Value;
    }

    [HttpGet]
    public IActionResult Get(string var1, int numberusers)
    {
        //...
    }
}

现在我添加了一个测试项目,我试图在其中使用 XUnit 和 Moq。我只是想创建一个控制器对象,就像我在一个非常简单的项目中所做的那样,但它在 this.When 中不起作用我试过:

CheckRegController cr = new CheckRegController();

它说:

There is no argument given that corresponds to the required formal parameter 'context' of 'CheckRegController.CheckRegController(ApplicationDbContext, IOptions)' XUnitTestProjectOA

然后我尝试了:

var moqHome = new Mock<ApplicationDbContext>();

但我不知道这样做是否正确,或者我需要提前做什么? 如何传递 _context_appsettings ??

你走在正确的轨道上。模拟依赖项并将它们注入被测对象。

//Arrange
var dbmock = new Mock<ApplicationDbContext>();
//...setup dbmock as needed to exercise test
var options = new Mock<IOption<AppSetting>();
var appSetting = new AppSetting {
    //...populate appSetting as needed to exercise test
};
options.Setup(_ => _.Value).Returns(appSetting);

var sut = new CheckRegController(dbMock.Object, options.Object);
var var1 = "testing";
var numberusers = 2;

//Act
var actual = sut.Get(var1,numberusers)

//Assert
//...assert expected behavior to actual.

我还建议抽象出上下文,使控制器更易于维护。