在使用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来说可能不是一个好问题。