代码审查:这是为异常编写单元测试的干净方法吗?



这里有人可以评论上述测试用例的质量吗?我在这里测试应该抛出的异常情况。我的意思是它可以工作,但它是否是针对期望应该抛出异常的情况进行单元测试的正确方法。

it('should throw exception if config.env.json is malformed', async () => {
// Arrange: beforeEach
const fakeFsStub = sinon.stub(File, 'readFileAsyc');
fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));
try {
// Act
await Configuration.getConfiguration('test');
chai.assert.fail('test case failed: [should throw exception if config.env.json is malformed]');
} catch (e) {
// Assert
chai.assert.equal('SyntaxError: Unexpected token } in JSON at position 6', e + '');
}
});

就我个人而言,我不喜欢必须编写多个失败条款。我认为这使测试更难阅读。另外,我会调整测试的结构。

describe("Configuration class", ()=>{
describe("#getConfiguration", ()=>{
describe("When the config.env is correctly formed.", ()=>{
// do some setup and assertions
})
describe("when the config.env.json is malformed", () =>{
let actualError
let fakeFsStub
before(async ()=>{
fakeFsStub = sinon.stub(File, 'readFileAsyc');
fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));
try {
await Configuration.getConfiguration('test');
} catch (e) {
actualError = e;
}
})
it('should call fs.readFileAsyc with correct args', ()=>{
// make an assertion
})
it('should throw an exception', () => {
chai.assert.equal('SyntaxError: Unexpected token } in JSON at position 6', actualError + '');
});
})
})
})

这只是我更喜欢编写单元测试的方式,因为它使我的断言保持不变。当您看到测试失败并且确切知道导致测试失败的断言时,这会很有帮助。此外,当设置逻辑引发错误并导致测试失败时,控制台输出将在 before 块中显示失败。

使函数异步意味着它将返回承诺而不是即时值。

因此,在柴如承诺的帮助下,您可以做到:

it('should throw an exception', async () => {
await expect(Configuration.getConfiguration('test')).to.eventually.be.rejectedWith(Error, 'SyntaxError: Unexpected token }');
});

同样在我看来,通过这种方式,您实际上可以检查本机 JSON.parse 是否运行良好,而不是测试您自己的代码。

我也想添加自己的答案:)我最终按照这里的建议重构了我的测试 https://codereview.stackexchange.com/questions/203520/writing-unit-tests-for-exception-should-be-thrown-case

另外,我喜欢接受答案的建议。我可能会在编写未来的测试时使用它。

it('should throw exception if config.env.json is malformed', async (done) => {
// Arrange: beforeEach
const fakeFsStub = sandbox.stub(File, 'readFileAsyc');
fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));
chai.assert.throws(() => {
// Act
Configuration.getConfiguration('test').catch((e) => {
chai.assert.instanceOf(e, SyntaxError);
chai.assert.isTrue(e.toString().startsWith('SyntaxError: Unexpected token } in JSON'));
done();
});
});
});

最新更新