How to: Use Junit to Test Java Command Line Program.

As the topic says and as the code below suggests.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import org.junit.Test;

public class TestSystemIN
{

	public static void printName(String name)
	{
		System.out.println("Hello " + name + "\r\n");
	}

	@Test
	public void testPrintName() throws IOException
	{
		// Simulate input
		String data = "John";
		InputStream stdin = System.in;
		try
		{
			System.setIn(new ByteArrayInputStream(data.getBytes()));
			Scanner scanner = new Scanner(System.in);
			String name = scanner.nextLine();
			// Print name
			printName(name);
		}
		finally
		{
			System.setIn(stdin);
		}

	}

}
Feb 13th, 2011

Comments