开玩笑 - 测试证书验证



寻求一些关于使用某些证书处理函数的Jest处理单元测试的最佳方法的建议。

我有一个验证函数,用于验证针对根 CA 传递的证书(通过和 API 调用(,另一个使用上述证书在将某些数据传递回调用方之前对其进行加密。

考虑到如何可靠地测试这一点,我想到了使用 OpenSSL 创建自己的 CA 和所需的测试证书的想法。我可以将它们作为文件保存在项目测试目录中,并在进一步将它们用作我正在测试的功能的模拟之前有一个测试用例来检查是否有效。

我在这里的想法是,测试证书可以毫无问题地保存到源代码管理中,并且将是健壮的测试用例。

这听起来像是一个合理的方法还是矫枉过正?

我的观点是,单元测试应该只在正面和负面场景中测试你的实现,并且应该模拟所有 API 调用。这样,您可以针对每个代码更改运行测试,如果服务不可用,它们不会失败。

下面是一个示例解决方案大纲:

import implementation from "./implementation";
import certificate from "./cerficiates/genuine";
import request from "request-library";
jest.mock("request-library");
describe("Certificate validation", () => {
describe("validate", () => {
describe("returning negative response", () => {
beforeAll(() => {
let result;
beforeAll(() => {
request.post.mockClear();
request.post.mockResolvedValue({
body: "invalid certificate",
});
result = implementation.validate(certificate);
});
it("should have made a post request with certificate", async () => {
await result;
expect(request.post).toHaveBeenCalledWith(
"http://validate.certificate.com",
{
body: certificate,
}
);
});
it("should return error", async () => {
await expect(result).rejects.toEqual(new Error("invlid certificate"));
});
});
});
describe("returning positive response", () => {
let result;
beforeAll(() => {
request.post.mockClear();
request.post.mockResolvedValue({
body: "valid certificate",
});
result = implementation.validate(certificate);
});
it("should have made a post request with certificate", async () => {
await result;
expect(request.post).toHaveBeenCalledWith(
"http://validate.certificate.com",
{
body: certificate,
}
);
});
it("should return true", async () => {
expect(await result).toBe(true);
});
});
});
});

此解决方案遵循单元测试的 FIRST 原则

✅ [F]:快速,不依赖任何本地/远程服务。不能失败,因为 测试超时/服务不可用

✅ [I]:不依赖任何东西

✅ [R]:可重复,因为它每次运行时都会重现相同的结果

✅ [S]:自我验证,因为它不会依赖任何东西来检查它是否必须通过或失败

✅ [T]:及时,因为您可以在实现之前/同时编写它

最新更新