gpt4 book ai didi

c# - 单元测试 WinForms

转载 作者:行者123 更新时间:2023-11-30 16:56:59 25 4
gpt4 key购买 nike

我是编程和 C# 的新手,被分配了为遗留代码编写单元测试的任务,为大数据库更改做准备。

我对单元测试的了解越多,我就越怀疑我的方法。

您将如何为以下内容编写单元测试?目前我刚刚对我的数据访问层方法进行单元测试,确保它们返回结果?但显然单元测试应该独立于任何外部环境?

当几乎所有内容都在调用数据库或存储过程时,我如何测试我的应用程序?

我的表单代码:

public void button1_Click(object sender, EventArgs e)
{
LoadAllCountries()
}

private static void LoadAllCountries()
{
List<nsHacAppMod.ViewCountryInfo> oReturn = moBusinessServices.GetAllCountries();
}

我的数据访问层

public List<nsAppMod.ViewCountryInfo> GetAllCountries()
{
List<nsAppMod.ViewCountryInfo> oReturn;

var oResult = from c in moDataContext.ViewCountryInfos
select c;

oReturn = oResult.ToList();

return oReturn;
}

我当前对此代码的单元测试,可以接受吗?如果不是,您会测试什么?

[Test]
public void LoadAllCountries()
{
hac.CatalogSamples cs = new hac.CatalogSamples();
var countries = cs.GetAllCountries().count();

Assert.GreaterOrEqual(countries 0);
}

最佳答案

如果您的上下文基于可以伪造的 IContext 等接口(interface),您可以对数据访问进行单元测试,然后您可以像 GetAllCountries() 方法一样只测试您尝试测试的代码。

但是,除了 try catch 之外,没有实际的逻辑可以测试。我是这样看的:如果它是一个没有逻辑的属性,或者也没有方法,那么它就不值得测试。使用类似 FakeItEasy 的模拟框架我会像这样测试这个方法:

    public class ClassToTest
{
internal virtual MoDataContext CreateContext()
{
return new MoDataContext();
}

public List<ViewCountryInfo> GetAllCountries()
{
List<ViewCountryInfo> oReturn = null;

try
{
var oResult = from c in this.CreateContext().ViewCountryInfos
select c;

oReturn = oResult.ToList();
}
catch (Exception)
{
}

return oReturn;
}

[Fact]
public void Test_GetAllCountries_ResultCountShouldBeGreaterThan0()
{
var fakeData = new List<ViewCountryInfo>();
fakeData.Add(new ViewCountryInfo());

var sut = A.Fake<ClassToTest>();
A.CallTo(sut).CallsBaseMethod();
A.CallTo(() => sut.CreateContext()).Returns(fakeData);

var result = sut.GetAllCountries();

Assert.IsTrue(result.Count() > 0);
}

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

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