gpt4 book ai didi

c# - 单元测试 C# [TestInitialize]

转载 作者:IT王子 更新时间:2023-10-29 04:03:26 24 4
gpt4 key购买 nike

我在 C# Web API Controller 上执行单元测试 - 每个 Controller 都需要几个参数来初始化。我目前在每个测试中都有以下代码,但它非常庞大。如何将此代码放入 [TestInitialize] 以便它在每次测试之前运行?

我尝试了以下方法,但显然它超出了测试方法的范围。

[TestInitialize]
public void TestInitialize()
{
APIContext apicon = new APIContext();
xRepository xRep = new xRepository(apicon);
var controller = new relevantController(cRep);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
relevantFactoryModel update = new relevantFactoryModel();
}

最佳答案

您可以将您需要的变量设置为测试类的字段,然后在TestInitialize方法中初始化它们。

class Tests 
{
// these are needed on every test
APIContext apicon;
XRepository xRep;
Controller controller;
RelevantFactoryModel update;

[TestInitialize]
public void TestInitialize()
{
apicon = new APIContext();
xRep = new xRepository(apicon);
controller = new relevantController(cRep);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
update = new relevantFactoryModel();
}
}

这样可以从每个测试中访问字段

关于c# - 单元测试 C# [TestInitialize],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26548017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com