Testing Output using assertEquals
Scenario1.java
public class Scenario { public int Square(int no) { return no*no; } }
SquareTest.java
public class SquareTest { @Test public void test() { int SquareNo = new Test1().Square(5); assertEquals(25, SquareNo); } }
Scenario2.java(word Counter)
public class Scenario2 { public int repeatedWords(String pWord) { int count = 0; for (int j = 0; j < pWord.length(); j++) { if(pWord.charAt(j) == 'a') { count++; } } return count; } }
RepeatTest.java
public class RepeatTest { @Test public void test() { Scenario2 objScenario2 = new Scenario2(); assertEquals(objScenario2.repeatedWords("alphabet"), 2); } }
Test suite is used to bundle a few unit test cases and run them together. In JUnit, both @RunWith and @SuiteClasses annotations are used to run the suite tests.
AllTests.java (TestSuite)
@RunWith(Suite.class) @SuiteClasses({ RepeatTest.class, SquareTest.class }) public class AllTests { }
Now Lets take a Real Life Scenario of Bank Account
Account.java
public class Account { public int Balance; public Account() { Balance = 0; } public int getAccBalance() { return Balance; } public void getCash(int pCash) { Balance = Balance - pCash; } public void putCash(int pCash) { Balance = Balance + pCash; } }
BankTest.java
public class BankTest { Account objAcc = new Account(); @Test public void checkAccBalanceTest() { assertEquals(objAcc.getAccBalance(), 0); } @Test public void checkBalAfterDepositTest() { objAcc.putCash(50); assertEquals(objAcc.getAccBalance(), 50); } @Test public void checkBalAfterWithdrawTest() { objAcc.getCash(30); assertEquals(objAcc.getAccBalance(), 20); } }
Points to Note
- The methods in BankTest ends with Test Suffix.This ensures the test cases are executed in order.
- The Account.java and BankTest.java are two different projects.In BankTest project the other project is added in Java Build Path