unit-testing - 您如何在 aws-cdk 单元测试中模拟现有的 vpc?
问题描述
我正在编写一个创建 ECS Fargate 堆栈的 AWS CDK 应用程序。它使用现有的 VPC 和现有的 ECR 存储库。简单地模拟我的接口,并返回 IVpc 和 IRepository 接口的模拟,就可以解决最初的问题,但是当 CDK 开始使用这些构造时,我会遇到更多错误。
const mockResources = mock<IExistingResources>(
{
getVpc: (scope: cdk.Construct, vpcId: string) => {
return mock<IVpc>();
},
getElasticContainerRepository: (scope: cdk.Construct, id: string, repositoryName: string) => {
return mock<IRepository>();
}
}
);
我收到此错误:
TypeError: Cannot destructure property 'subnetIds' of 'baseProps.vpc.selectSubnets(...)' as it is undefined.
这似乎是一个可能的“黑洞”,我需要了解模拟的每一种用法并对其进行解释。我正在寻找一种更好的方法来一致地对现有资源进行建模,以便我可以测试我的新代码。任何意见,将不胜感激。
解决方案
对于遇到此问题的任何人,我决定构建一个具有已知参数的 VPC 以进行测试。此 VPC 是从模拟fromLookup
函数返回的。
例如:构建 VPC
function buildVpc(scope: cdk.Construct, vpcId:string): IVpc {
return new Vpc(scope, vpcId, {
cidr: '10.0.0.0/16',
maxAzs: 2,
subnetConfiguration: [{
cidrMask: 26,
name: 'isolatedSubnet',
subnetType: SubnetType.PUBLIC,
}],
natGateways: 0
});
}
然后在我ExistingResources
班级的模拟中使用vpc,
const mockResources = mock<IExistingResources>(
{
getVpc: (scope: cdk.Construct, vpcId: string) => {
return buildVpc(scope, vpcId);
},
getElasticContainerRepository: (scope: cdk.Construct, id: string, repositoryName: string) => {
return mock<IRepository>();
}
}
);
这允许我在断开连接的环境中进行快照测试。
推荐阅读
- python - 如何将列表中的确切字符串匹配到考虑空格的较大字符串?
- angular - 使用 asyncScheduler 和 flush 进行角度测试 - 为什么使用 flush() 失败?
- angular - mat-checkbox and checked value (A) or checked value (D)
- mysql - 从 mySQL 返回未定义
- c# - 结构类型的扩展方法
- python - 如何从网络抓取的混合字符串中分离价格(数字)
- powershell - 如何将 PowerShell 运行空间 stderr、stdout 等组合成一个流
- c - 错误:从 fork() 子调用 sqlite3_exec() 时数据库被锁定
- c++ - std::chrono 在 arm 中的行为不同
- python - 用python绘制正值的小提琴图