Please, I am new to Java. How can I write a JUnit test for the program below:
Program to Test:
package codekeeper;
/**
*
* @author henryjoseph
*/
import java.util.*;
import java.io.*;
public class CodeKeeper {
ArrayList<String> list; //no specific amount..
String[] codes = {"alpha","lambda","gamma","delta","zeta"};
public CodeKeeper (String[] userCodes)
{
list = new ArrayList<String>();
for(int i =0; i<codes.length;i++)
addCode(codes[i]);
for(int i =0; i<userCodes.length;i++)
addCode(userCodes[i]);
for(String code:list)
System.out.println(code);
}
final void addCode(String code)
{
if(!list.contains(code))
list.add(code);
}
public static void main(String[] args) {
System.out.print("Enter your name and press Enter: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = null;
String[] argu = new String[] {name};
try {
name = br.readLine();
argu = new String[] {name} ;
}catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
CodeKeeper keeper = new CodeKeeper(argu);
}
}
Sample Test Code:
public class MyClassTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}
Is this a standard way of writing the Junit Tests?
Some background first then some examples. When you write unit tests against your code you are testing a very specific and finite case of your application. What that means is that each unit test should cover at most one (1) scenario that a function (method) can receive. If you want to test multiple functions together you would be performing integration testing. Now if we take the following function that you have declared:
Assume that
codeKeeperis properly initialized.An appropriate unit test would look like this:
Another appropriate usage is the following: