AWS CDK Unittest不能模拟NetworkLoadBalancer资源,并且此问题会导致难以进行单元测试。为了解决这个问题,可以使用AWS CDK提供的CDKIntegrationTest工具和MockIntegrationTest构建一组集成测试来测试网络负载平衡器资源。以下是一个示例代码,该代码使用了CDKIntegrationTest和MockIntegrationTest:
import boto3
from aws_cdk import (
core as cdk,
aws_ec2 as ec2,
aws_elasticloadbalancingv2 as elbv2,
testing as cdk_testing
)
class MyStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc(self, "MyVPC")
alb = elbv2.NetworkLoadBalancer(
self,
"MyALB",
vpc=vpc,
internet_facing=False,
load_balancer_name="MyLoadBalancer"
)
core.CfnOutput(self, "ALBARN", value=alb.load_balancer_arn)
class TestMyStack(unittest.TestCase):
def test_stack(self):
app = cdk.App()
MyStack(app, "stack")
# create a mock of the network load balancer
mock_elbv2 = cdk_testing.MockAws(lambda: boto3.Session())
mock_elbv2.add_mock("elbv2", "create_load_balancer", side_effect=Exception("cannot create network load balancer"))
mock_elbv2.add_mock("elbv2", "delete_load_balancer", return_value={})
# prepare the integration test
integ_test = cdk_testing.CDKIntegrationTest(
app,
"test-stack",
cloud_assembly_subdirectory="test-fixtures/test-stack.out"
)
# provide the mock to the integration test
integ_test.set_aws(mock_elbv2.aws())
# run the integration test and validate that the cloudformation stack was created successfully
integ_test.synth()
integ_test.deploy(expect_changes=True)
stack = integ