我们可以在多大程度上重构单元测试



在使用Jasmine测试框架时,我遇到了一个代码片段,其中expect写在子函数中,该子函数在it()中调用,但在it()本身中不调用。写这篇文章的原因是,他们试图比较类似的对象,他们refactored测试代码,并将这个expect移到子函数中。现在,我们在it()中没有expect,而是有一个具有expect的方法调用。

describe("bla bla", function() { //for nunit, junit guys, this is testSuite()
    function somefunc() { //this is [test]
    //do some stuff and generate object
    expect(someObject).toEqual(otherObject); //expect is assert
}
   it("some case", function() {
       //do some stuff
       somefunc();
   });
   it("some other case", function() {
       //do some other stuff
       somefunc();
   });
});

现在,这种测试代码值得鼓励吗?我们能有it()而没有expect吗?

我认为下面的两个例子都可读。如果assertExpected()为otherObject做了某种设置,那么第一个例子可能更可读。

describe("bla bla", function() { //for nunit, junit guys, this is testSuite()
    function assertExpected() { //this is [test]
      //do some stuff and generate object
      expect(someObject).toEqual(otherObject); //expect is assert
    }
   it("some case", function() {
       // Arrange
       var someObject;
       // Act
       someObject = testMethod('foo');
       // Assert
       assertExpected();
   });
   it("some other case", function() {
       // Arrange
       var otherObject, someObject = testMethod('foo');
       // Act
       someObject = testMethod('foo');
       // Assert
       assert(someObject(foo)).toEqual(otherObject);
   });
});

我认为这里的决定因素应该是决定房子的风格并坚持下去。这里没有明确的赢家,这个问题对SO来说可能不是一个好问题。

最新更新