I had a program to check the stack status of AWS CloudFormation. It is necessary to test all statuses because the processing is different for each status returned.
You can't control the status of the AWS CloudFormation stack here.
Write test code in Junit, I decided to specify (mock) the status returned by the API.
Below is the code part to be tested
describeStacks.java
/*Creating a client for executing CloudFormation API*/
AmazonCloudFormationAsync CFclient = AmazonCloudFormationAsyncClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("hope", "huga")))
.build();
/*DescribeStacks Specify the target stack name*/
DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
describeStacksRequest.withStackName("hogestack");
/*API to get the stack status here(describeStacks)(Where you want to mock)*/
DescribeStacksResult describeStacksResult = CFclient.describeStacks(describeStacksRequest);
describeStacksTest.java
@RunWith(MockitoJUnitRunner.class)
public class describeStacksTest {
/*Declare the class to mock*/
@Mock AmazonCloudFormationAsync AmazonCloudFormationMock;
/*Specify the class to inject the class to be mocked*/
@InjectMocks describeStacksClass describeStacks = new describeStacksClass();
@Before
public void init() {
/*Mock initialization*/
MockitoAnnotations.initMocks(this);
}
@Test
public void Controlling stack status() {
/*Create a class of return values when describeStacks is executed*/
DescribeStacksResult describeStacksResult = new DescribeStacksResult();
Stack stacks = new Stack();
stacks.setStackStatus(StackStatus.CREATE_COMPLETE); //Set StackStatus(This time CREATE_Specify the status of COMPLETE)
describeStacksResult.withStacks(stacks);
/*Create a class with the same arguments that the test target executes*/
DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest();
describeStacksRequest.withStackName("hogestack");
/*Specify the run-time arguments and return values of describeStacks for the mocked class*/
when(AmazonCloudFormationMock.describeStacks(DescribeStacksRequest)).thenReturn(describeStacksResult);
Since the AmazonCloudFormationAsync class was public, it was easily mocked. Since it is a class provided as an API, it was easy to mock because it was public. It's true that setters are easy for Resule classes (did you expect AWS to be mocked or stubized?) I think other APIs can be tested in the same way.
Recommended Posts