-1

I am writing QUnit tests for my JavaScript web app. After reading the QUnit API documentation I was unable to find any standards for labeling modules, tests, and asserts.

The API descriptions and examples are pretty rudimentary:

Module name: Label for this group of tests. Example: module("group a");

Test title: Title of unit being tested. Example: test("hello test", function(){});

Assert message: A short description of the assertion. Example: ok(true, "true succeeds");

I found articles out there regarding Unit Tests at large: What are some popular naming conventions for Unit Tests? and Unit test naming best practices.

However, I was hoping there was an established/generally accepted standard that was specific to QUnit's Module->Test->Assert pattern. Are there any?

4

1 回答 1

1

无论您使用哪种测试框架,也无论您是在编写客户端还是服务器端单元测试,采用一些“命名约定”的主要关注点是确保测试名称清楚地向每个人说明系统是什么以及正在测试的行为。

假设我们要测试这段代码:

var MyClass = (function () {
    function MyClass() {
        this.defaultMessage = "Hello person without a name";
    }
    MyClass.prototype.getHelloMessage = function (firstName, lastName) {
        if (!firstName && !lastName) {
            return this.defaultMessage;
        }
        var message = "Hello";
        if (lastName) {
            message += " " + lastName;
        }
        if (firstName) {
            if (lastName) {
                message += ",";
            }
            message += " " + firstName;
        }    
        return message;
    };        
    return MyClass;
})();

    上面的代码只是用给定的输入参数(如果有的话)格式化一个简单的消息,如果没有指定参数,则返回一个默认消息。

对我来说,模块名称将是类名和分隔符,以使测试名称列表更具可读性:

QUnit.module("MyClass tests - ");

可以简单地命名测试:

test("getHelloMessage test", function () {}

并在一个文本中断言所有期望。

我更喜欢更详细的方法,这样可以清楚地理解每个测试的目的:

test("getHelloMessage without input parameters should return default message", function () {});
test("getHelloMessage with only lastName should not display a comma", function () {});
test("getHelloMessage with only firstName should not display a comma", function () {});

这样,每个测试都有一个明确的目的,它们将保持尽可能小,当一个测试失败时,很容易理解你的代码的哪一部分受到了最新更改的影响。

好的标准是团队所有成员都同意的标准,它将帮助每个人发现和解决错误,并帮助他们编写更好的单元测试。

于 2013-07-25T12:01:51.297 回答