构造函数的单元测试 [英] Unit-testing of a constructor

查看:91
本文介绍了构造函数的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究单元测试的实验室实践,下面是我正在测试的应用程序中的一段代码.大多数单元测试已经完成,但关于下面的构造函数,我就是不知道如何测试它.例如,构造函数究竟对数组元素做了什么?什么是测试构造函数的好方法?

I'm working on a laboratory practical with unit-testing, and below is a piece of code from the application that i'm testing. Most of the unit-testings are finished, but regarding the constructor below I just can't figure out how to test it. For example, what exactly is the constructor doing with the array elements? What would be a good way of testing the construtor?

也许有一个善良的灵魂可以让我朝着正确的方向前进?

Is there maybe a kind soul out there who could give me a kick in the right direction?

  public struct Point { 
    public int x, y;

    public Point(int a, int b) {
      x = a;
      y = b;
    }
  }

...

  public Triangle(Point[] s) {
    sides = new double[s.Length];
    sides[0] = Math.Sqrt(Math.Pow((double)(s[1].x - s[0].x), 2.0) + Math.Pow((double)(s[1].y - s[0].y), 2.0));
    sides[1] = Math.Sqrt(Math.Pow((double)(s[1].x - s[2].x), 2.0) + Math.Pow((double)(s[1].x - s[2].x), 2.0));
    sides[2] = Math.Sqrt(Math.Pow((double)(s[2].x - s[0].x), 2.0) + Math.Pow((double)(s[2].x - s[0].x), 2.0));
  }

...

        [TestMethod()]
        public void TriangleConstructorTest1()
        {
            Point[] s = null; // TODO: Initialize to an appropriate value
            Triangle target = new Triangle(s);
            Assert.Inconclusive("TODO: Implement code to verify target");
        }

推荐答案

你说的是 Traingle-constructor,不是吗?

You are talking about the Traingle-constructor, aren't you?

看起来它是使用勾股定理来计算三角形的长度侧面.
所以你应该测试一下这个计算是否正确.

It looks like it is using the Pythagorean theorem to calculate the length of the triangle sides.
So you should test whether this calculation is done correctly.

此外,您可以检查构造函数是否检测到无效参数,例如:

In addition, you could check if the constructor detects invalid arguments, e.g.:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Cannot_Create_Passing_Null()
{
   new Triangle(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Cannot_With_Less_Than_Three_Points()
{
   new Triangle(new[] { new Point(0, 0), new Point(1, 1) });
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Cannot_Create_With_More_Than_Three_Points()
{
   new Triangle(new[] { new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3) });
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Cannot_Create_With_Two_Identical_Points()
{
   new Triangle(new[] { new Point(0, 0), new Point(0, 0), new Point(1, 1) });
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Cannot_Create_With_Empty_Array()
{
   new Triangle(new Point[] { });
}

这篇关于构造函数的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆