Skip to content

Commit 61ad2a8

Browse files
committed
Added unit testing sample code
1 parent d18fa28 commit 61ad2a8

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,84 @@ Complete reference for Android Testing with examples.
4040
## Local
4141

4242
### JUnit basics
43+
44+
```java
45+
public class Calculator {
46+
47+
public int add(int op1, int op2) {
48+
return op1 + op2;
49+
}
50+
51+
public int diff(int op1, int op2) {
52+
return op1 - op2;
53+
}
54+
55+
public double div(int op1, int op2) {
56+
// if (op2 == 0) return 0;
57+
return op1 / op2;
58+
}
59+
}
60+
61+
// Unit tests
62+
public class CalculatorTest {
63+
64+
private Calculator calculator;
65+
66+
@Before
67+
public void setup() {
68+
calculator = new Calculator();
69+
System.out.println("Ready for testing!");
70+
}
71+
72+
@After
73+
public void cleanup() {
74+
System.out.println("Done with unit test!");
75+
}
76+
77+
@BeforeClass
78+
public static void testClassSetup() {
79+
System.out.println("Getting test class ready");
80+
}
81+
82+
@AfterClass
83+
public static void testClassCleanup() {
84+
System.out.println("Done with tests");
85+
}
86+
87+
@Test
88+
public void testAdd() {
89+
calculator = new Calculator();
90+
int total = calculator.add(4, 5);
91+
assertEquals("Calculator is not adding correctly", 9, total);
92+
}
93+
94+
@Test
95+
public void testDiff() {
96+
calculator = new Calculator();
97+
int total = calculator.diff(9, 2);
98+
assertEquals("Calculator is not subtracting correctly", 7, total);
99+
}
100+
101+
@Test
102+
public void testDiv() {
103+
calculator = new Calculator();
104+
double total = calculator.div(9, 3);
105+
assertEquals("Calculator is not dividing correctly", 3.0, total, 0.0);
106+
}
107+
108+
@Ignore
109+
@Test(expected = java.lang.ArithmeticException.class)
110+
public void testDivWithZeroDivisor() {
111+
calculator = new Calculator();
112+
double total = calculator.div(9, 0);
113+
assertEquals("Calculator is not handling division by zero correctly", 0.0, total, 0.0);
114+
}
115+
}
116+
117+
```
118+
119+
120+
43121
### Beyond JUnit basics
44122
### Local test setup and execution
45123
### Adding local tests and failure

0 commit comments

Comments
 (0)