5

假设我有两个类BookLibrary如下所示:

var Book = function(title, author)
{
   this.title = title;
   this.author = author;
};

var Library = function()
{
   var dbName = 'test';

   this.getLibrary = function() {
      return JSON.parse(window.localStorage.getItem(dbName));
   };

   this.save = function(library) {
      window.localStorage.setItem(dbName, JSON.stringify(library));
   };
}

Library.prototype.addBook = function(book) {
   var library = this.getLibrary();
   library.push(book);

   this.save(library);

   return library;
};

Library.prototype.removeBook = function(book) {
   var library = this.getLibrary();

   // Find and delete the right book

   this.save(library);

   return library;
};

我的问题是:如何Library使用 QUnit 对类进行单元测试以进行真正的原子和独立测试?

我写了这个测试函数,但它并没有让我满意。它似乎不是非常原子和独立的,因为它混合了我认为应该独立测试的几个功能。我想知道是否有更好的方法,或者我已经在测试它了。

test("test", function() {
   var library = new Library();

   deepEqual(library.getLibrary(), []);

   // Add book1
   var book1 = new Book("A book", "An author");
   deepEqual(library.addBook(book1), [book1]);
   deepEqual(library.getLibrary(), [book1]);

   // Add book2    
   book2 = new Result("A new book", "Another author");
   deepEqual(library.addBook(book2), [book2, book1]);
   deepEqual(library.getLibrary(), [book2, book1]]);

   // Remove book1
   deepEqual(library.removeResult(book1), [book2]);
   deepEqual(library.getLibrary(), [book2]);

   // Remove book2
   deepEqual(library.removeResult(book2), []);
   deepEqual(library.getLibrary(), []);
});
4

1 回答 1

3

避免编写依赖于您正在测试的单元的内部状态的“综合”测试。对特定行为进行细粒度测试,而不是声明:

test("addBooksReturnsLibrary", function(){
    var l = new Library();
    l.addBook(new Book(...));
    l.addBook(new Book(...));
    var addBooksRetval = l.addBook(new Book(...));
    deepEqual(addBooksRetval, l.getLibrary();
});

test("libraryContainsAddedBook"), function() {
    var l = new Library();
    var b = new Book(...);
    l.addBook(b);
    notEqual(-1, library.indexOf(b));
});

// etc and so forth

大量使用deepEqual似乎经常是一种测试气味。例如,如果您确实需要按特定顺序将书籍放在图书馆中,我会说最好专门测试这些排序约束。

于 2012-10-09T00:31:09.350 回答