代码审查:这是一个干净的方式来编写单元测试异常应抛出的情况吗?

问题描述 投票:-1回答:3

这里的任何人都可以评论上述测试用例的质量吗?我在这里测试应该抛出的异常场景。我的意思是它的工作原理,但它是正确的单元测试方法,期望是应该抛出异常的场景。

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 + '');
  }
});
javascript unit-testing jasmine sinon
3个回答
1
投票

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

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

这就是我更喜欢编写单元测试的方式,因为它使我的单个断言保持不变。当您看到测试失败并确切知道哪个断言导致测试失败时,这会很有用。此外,当您的设置逻辑抛出错误并导致测试失败时,控制台输出将在前一个块中说它失败。


1
投票

使函数异步意味着它将返回promise而不是立即值。

所以在chai-as-promised的帮助下你可以这样做:

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

另外在我看来,你实际上检查本机JSON.parse是否运行良好,而不是测试自己的代码。


1
投票

我想添加我自己的答案:)我最终根据这里的建议重构我的测试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();
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.