Arrange-Act-Assert Pattern
Arrange-Act-Assert Pattern
The Arrange-Act-Assert Pattern is a method used in software testing,
particularly with the unit test frameworks, to make the structure of tests clear and consistent.
AAA pattern for writing unit tests for the method under test. AAA stands for:
- Arrange
- Act
- Assert
Arrange
Set up the initial conditions and inputs for your test. This involves creating and configuring objects and variables needed for the test.
Arrange – set up, create objects, data, etc
Act
Perform the actual action that you want to test. This usually involves calling a method or function.
Act – Invoke the method under test
Assert
Check that the expected outcome has been achieved. This involves comparing the actual result
with the expected result and using assertions to verify that the test has passed or failed.
Assert – Verify pass or fail
Example
The code example is as shown below:
package com.testingdocs.calculator.tests;
//Arrange-Act-Assert pattern
import com.testingdocs.calculator.Calculator;
import org.junit.Test;
import org.junit.Assert;
import org.junit.Before;
public class CalculatorTest {
private Calculator objCalcUnderTest;
@Before
public void setUp() {
//Arrange
objCalcUnderTest = new Calculator();
}
@Test
public void testAdd() {
int a = 15; int b = 20;
int expectedResult = 35;
//Act
long result = objCalcUnderTest.add(a, b);
//Assert
Assert.assertEquals(expectedResult, result);
}
@Test
public void testSubtract() {
int a = 25; int b = 20;
int expectedResult = 5;
long result = objCalcUnderTest.subtract(a, b);
Assert.assertEquals(expectedResult, result);
}
@Test
public void testMultiply() {
int a = 10; int b = 25;
long expectedResult = 250;
long result = objCalcUnderTest.multiply(a, b);
Assert.assertEquals(expectedResult, result);
}
@Test
public void testDivide() {
int a = 56; int b = 10;
double expectedResult = 5.6;
double result = objCalcUnderTest.divide(a, b);
Assert.assertEquals(expectedResult, result,0.00005);
}
@Test(expected = IllegalArgumentException.class)
public void testDivideByZero() {
int a = 15; int b = 0;
objCalcUnderTest.divide(a, b);
}
}