代码审查:这是为应该抛出异常的情况编写单元测试的干净方法吗?

Code Review: Is this a clean way to write unit test for exception should be thrown case?

这里有人可以评论一下上面测试用例的质量吗?我在这里测试应该抛出异常的场景。我的意思是它有效,但它是否是对期望抛出异常的场景进行单元测试的正确方法。

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 + '');
      });
    })
  })
})

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

使函数异步意味着它将 return 承诺而不是立即值。

因此,在 chai-as-promised 的帮助下,您可以这样做:

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();
    });
  });
});