c# - 如何在 .net 中使用 C# 对默认构造函数类进行单元测试?

标签 c# unit-testing constructor

我在 Visual Studio 2012 中有一个 Windows 类库项目,我正在尝试测试默认构造函数。

我的构造函数是:

  public Form()
    {
        Items = new List<IFormItem>();
        Items.Add(new FormItem());
        Items[0].Type = ItemTypes.TextBox;
        Items[0].Text = "User ID";
        Items[0].X = 100;
        Items[0].Y = 100;
        Items[0].Height = 30;
        Items[0].Width = 100;
        Items.Add(new FormItem());
        Items[1].Type = ItemTypes.Button;
        Items[1].Text = "Log In";
        Items[1].X = 130;
        Items[1].Y = 170;
        Items[1].Height = 30;
        Items[1].Width = 70;
    } 

我将如何测试它?

    [TestMethod]
    public void GetForm()
    {
        Form frm = new Form();

        //what to write here
    }

我只是想测试构造函数是否被调用。

最佳答案

试试这个:

[TestMethod]
public void GetForm()
{
    Form frm = new Form(); // the constructor is called here, this is your ACT

    var expectedNumberOfItems = 2;
    var expectedType = ItemTypes.Button;

    Assert.AreEqual(expectedNumberOfItems, frm.Items.Count, "frm.Items.Count");

    Assert.AreEqual(expectedType, frm.Items[0].Type, "frm.Items[0].Type");
    // etc...
}

关于c# - 如何在 .net 中使用 C# 对默认构造函数类进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20210827/

相关文章:

C# AssemblyFileVersion 在程序中的使用

c# - Linq C# 基于最大值

c# - ASP.Core 使用 Axios 上传图片

python - IntEnum 返回 AttributeError : can't set attribute

java - 了解 NoSuchMethod 异常中的方法签名

c# - LINQ:如何通过对每个元素执行计算来转换列表

c# - 组织执行测试的方法 - C#

c# - 单元测试消息

C++ 调用不同的类构造函数,避免切换

c++ - 定义类的类枚举常量而不提供对类构造函数的访问