From 793c42e8fe00936cec3de83ca675d4821c169594 Mon Sep 17 00:00:00 2001 From: Giles Gaskell Date: Mon, 18 Dec 2017 18:54:20 +1100 Subject: [PATCH] Refactor App and made AppTest properly test App. * Update version of junit dependency in 'pom.xml' file (to 4.11) so that org.junit dependencies in AppTest could be imported. --- pom.xml | 2 +- src/main/java/com/mycompany/app/App.java | 18 ++++-- src/test/java/com/mycompany/app/AppTest.java | 58 ++++++++++++-------- 3 files changed, 48 insertions(+), 30 deletions(-) diff --git a/pom.xml b/pom.xml index 46ef87c0f6..19ee4305a8 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ junit junit - 3.8.1 + 4.11 test diff --git a/src/main/java/com/mycompany/app/App.java b/src/main/java/com/mycompany/app/App.java index 77cf3e055b..5a6d57214d 100644 --- a/src/main/java/com/mycompany/app/App.java +++ b/src/main/java/com/mycompany/app/App.java @@ -2,12 +2,20 @@ /** * Hello world! - * */ -public class App +public class App { - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); + + private final String message = "Hello World!"; + + public App() {} + + public static void main(String[] args) { + System.out.println(new App().getMessage()); } + + private final String getMessage() { + return message; + } + } diff --git a/src/test/java/com/mycompany/app/AppTest.java b/src/test/java/com/mycompany/app/AppTest.java index 3355990039..908bac851a 100644 --- a/src/test/java/com/mycompany/app/AppTest.java +++ b/src/test/java/com/mycompany/app/AppTest.java @@ -1,38 +1,48 @@ package com.mycompany.app; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.Before; +import org.junit.Test; +import org.junit.After; +import static org.junit.Assert.*; /** * Unit test for simple App. */ -public class AppTest - extends TestCase +public class AppTest { - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + @Before + public void setUpStreams() { + System.setOut(new PrintStream(outContent)); } - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); + @Test + public void testAppConstructor() { + try { + new App(); + } catch (Exception e) { + fail("Construction failed."); + } } - /** - * Rigourous Test :-) - */ - public void testApp() + @Test + public void testAppMain() { - assertTrue( true ); + App.main(null); + try { + assertEquals("Hello World!" + System.getProperty("line.separator"), outContent.toString()); + } catch (AssertionError e) { + fail("\"message\" is not \"Hello World!\""); + } } + + @After + public void cleanUpStreams() { + System.setOut(null); + } + }