diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..dfa1b27 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: java +script: mvn test -f ./source/pom.xml +jdk: + - oraclejdk8 + - oraclejdk7 + - openjdk7 \ No newline at end of file diff --git a/README.md b/README.md index 2a580ec..e627674 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,11 @@ You can purchase the book on leanpub: https://leanpub.com/javaForTesters * Twitter: @eviltester ### Note: -This code is an extract from the actual source used to create the book. The actual source has embedded macros to allow the book to be automatically generated. While the extraction process has been tested, it may still contain errors. If you find differences from the book, or discover errors in this code, please let the author know. All tests have been run prior to the source release. +This code is an extract from the actual source used to create the book. The actual source has embedded macros to allow the book to be automatically generated. While the extraction process has been tested, it may still contain errors. If you find differences from the book, or discover errors in this code, please let the author know. All @Test code has been run prior to the source release. + +You can see a cloud build of the code provided by [travis-ci.orgtravis-ci.org/eviltester/javaForTestersCode](https://travis-ci.org/eviltester/javaForTestersCode). + +![Build Status](https://travis-ci.org/eviltester/javaForTestersCode.svg) License ------- diff --git a/source/reportingpom.xml b/source/reportingpom.xml index ce11c2f..4c4ca97 100644 --- a/source/reportingpom.xml +++ b/source/reportingpom.xml @@ -15,7 +15,7 @@ http://maven.apache.org/surefire/maven-surefire-plugin/usage.html http://maven.apache.org/surefire/maven-surefire-report-plugin/report-mojo.html - mvn clean test -Dmaven.source=reportingpom.xml + mvn clean surefire-report:report -Dmaven.source=reportingpom.xml --> diff --git a/source/src/main/java/com/javafortesters/classes/AnEmptyClass.java b/source/src/main/java/com/javafortesters/classes/AnEmptyClass.java deleted file mode 100644 index ebffcd1..0000000 --- a/source/src/main/java/com/javafortesters/classes/AnEmptyClass.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.javafortesters.classes; - -public class AnEmptyClass { -} diff --git a/source/src/main/java/com/javafortesters/domainentities/User.java b/source/src/main/java/com/javafortesters/domainentities/User.java index 1d9b4e1..42a0600 100644 --- a/source/src/main/java/com/javafortesters/domainentities/User.java +++ b/source/src/main/java/com/javafortesters/domainentities/User.java @@ -2,7 +2,6 @@ public class User { - private String username; private String password; @@ -10,7 +9,6 @@ public User(){ this("username", "password"); } - public User(String username, String password) { this.username = username; this.password = password; @@ -31,4 +29,4 @@ public void setPassword(String password) { public String getPermission() { return "Normal"; } -} \ No newline at end of file +} diff --git a/source/src/main/java/com/javafortesters/domainentities/UserComparator.java b/source/src/main/java/com/javafortesters/domainentities/UserComparator.java index 437fed1..52ea252 100644 --- a/source/src/main/java/com/javafortesters/domainentities/UserComparator.java +++ b/source/src/main/java/com/javafortesters/domainentities/UserComparator.java @@ -36,9 +36,3 @@ public int compare(Object oUser1, Object oUser2) { return val; } } - -/* -// add the following line just before return val; to see the comparator in action - System.out.println("Compare " + user1.getUsername() + - " with " + user2.getUsername() + " = " + val); -*/ \ No newline at end of file diff --git a/source/src/main/java/com/javafortesters/domainentities/interim/User.java b/source/src/main/java/com/javafortesters/domainentities/interim/User.java index 1198bd4..e1193d0 100644 --- a/source/src/main/java/com/javafortesters/domainentities/interim/User.java +++ b/source/src/main/java/com/javafortesters/domainentities/interim/User.java @@ -17,6 +17,11 @@ public User(){ password = "password"; } + public User(String username, String password) { + this.username = username; + this.password = password; + } + public String getUsername() { return username; } diff --git a/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/User.java b/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/User.java index 7b16dda..8b6c87e 100644 --- a/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/User.java +++ b/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/User.java @@ -27,7 +27,6 @@ public User(String username, String password) throws InvalidPassword{ } public void setPassword(String password) throws InvalidPassword { - if(password.length()<7){ throw new InvalidPassword("Password must be > 6 chars"); } diff --git a/source/src/test/java/com/javafortesters/unusedCode/UserPasswordExceptionsTest.java b/source/src/test/java/com/javafortesters/booksupport/unusedCode/UserPasswordExceptionsTest.java similarity index 95% rename from source/src/test/java/com/javafortesters/unusedCode/UserPasswordExceptionsTest.java rename to source/src/test/java/com/javafortesters/booksupport/unusedCode/UserPasswordExceptionsTest.java index 3988e84..f3ecd4b 100644 --- a/source/src/test/java/com/javafortesters/unusedCode/UserPasswordExceptionsTest.java +++ b/source/src/test/java/com/javafortesters/booksupport/unusedCode/UserPasswordExceptionsTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.unusedCode; +package com.javafortesters.booksupport.unusedCode; import com.javafortesters.domainentities.interim.exceptions.User; diff --git a/source/src/main/java/com/javafortesters/classes/AClassWithAMethod.java b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AClassWithAMethod.java similarity index 65% rename from source/src/main/java/com/javafortesters/classes/AClassWithAMethod.java rename to source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AClassWithAMethod.java index b92d462..8ab0ad1 100644 --- a/source/src/main/java/com/javafortesters/classes/AClassWithAMethod.java +++ b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AClassWithAMethod.java @@ -1,4 +1,4 @@ -package com.javafortesters.classes; +package com.javafortesters.chap001basicsofjava.examples.classes; public class AClassWithAMethod { diff --git a/source/src/test/java/com/javafortesters/junit/ASysOutJunitTest.java b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/ASysOutJunitTest.java similarity index 71% rename from source/src/test/java/com/javafortesters/junit/ASysOutJunitTest.java rename to source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/ASysOutJunitTest.java index 95da6de..2b1f564 100644 --- a/source/src/test/java/com/javafortesters/junit/ASysOutJunitTest.java +++ b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/ASysOutJunitTest.java @@ -1,6 +1,5 @@ -package com.javafortesters.junit; +package com.javafortesters.chap001basicsofjava.examples.classes; -import com.javafortesters.classes.AClassWithAMethod; import org.junit.Test; public class ASysOutJunitTest { diff --git a/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AnEmptyClass.java b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AnEmptyClass.java new file mode 100644 index 0000000..4f5fd47 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap001basicsofjava/examples/classes/AnEmptyClass.java @@ -0,0 +1,4 @@ +package com.javafortesters.chap001basicsofjava.examples.classes; + +public class AnEmptyClass { +} diff --git a/source/src/test/java/com/javafortesters/myfirsttest/MyFirstTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTest.java similarity index 79% rename from source/src/test/java/com/javafortesters/myfirsttest/MyFirstTest.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTest.java index 96d70fe..b58223f 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/MyFirstTest.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.myfirsttest; +package com.javafortesters.chap003myfirsttest.examples; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/source/src/test/java/com/javafortesters/myfirsttest/examples/MyFirstTestDifferentAsserts.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTestDifferentAsserts.java similarity index 80% rename from source/src/test/java/com/javafortesters/myfirsttest/examples/MyFirstTestDifferentAsserts.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTestDifferentAsserts.java index 18e70e2..886606a 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/examples/MyFirstTestDifferentAsserts.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/MyFirstTestDifferentAsserts.java @@ -1,4 +1,4 @@ -package com.javafortesters.myfirsttest.examples; +package com.javafortesters.chap003myfirsttest.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethod/MyFirstTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethod/MyFirstTest.java new file mode 100644 index 0000000..143987f --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethod/MyFirstTest.java @@ -0,0 +1,7 @@ +package com.javafortesters.chap003myfirsttest.examples.interim.emptyMethod; + +public class MyFirstTest { + + public void canAddTwoPlusTwo(){ + } +} diff --git a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethodTestAnnotated/MyFirstTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethodTestAnnotated/MyFirstTest.java similarity index 54% rename from source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethodTestAnnotated/MyFirstTest.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethodTestAnnotated/MyFirstTest.java index 9ec7f3b..94844fc 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethodTestAnnotated/MyFirstTest.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyMethodTestAnnotated/MyFirstTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.myfirsttest.interim.emptyMethodTestAnnotated; +package com.javafortesters.chap003myfirsttest.examples.interim.emptyMethodTestAnnotated; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyWithTemplate/MyFirstTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyWithTemplate/MyFirstTest.java similarity index 68% rename from source/src/test/java/com/javafortesters/myfirsttest/interim/emptyWithTemplate/MyFirstTest.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyWithTemplate/MyFirstTest.java index c0ed69e..159c36f 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyWithTemplate/MyFirstTest.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/interim/emptyWithTemplate/MyFirstTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.myfirsttest.interim.emptyWithTemplate; +package com.javafortesters.chap003myfirsttest.examples.interim.emptyWithTemplate; /** * Created with IntelliJ IDEA. diff --git a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClass.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClass.java similarity index 85% rename from source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClass.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClass.java index d5bf55a..e78a5ca 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClass.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClass.java @@ -1,11 +1,10 @@ -package com.javafortesters.myfirsttest.examples.naming; +package com.javafortesters.chap003myfirsttest.examples.naming; import org.junit.Test; import static org.junit.Assert.assertTrue; public class NameClass { - @Test public void whenClassNameHasNoTestInItThenItIsNotRun(){ // this test will not run from maven so i can make diff --git a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClassTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClassTest.java similarity index 83% rename from source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClassTest.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClassTest.java index 248823b..f3ec8b2 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameClassTest.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameClassTest.java @@ -1,11 +1,10 @@ -package com.javafortesters.myfirsttest.examples.naming; +package com.javafortesters.chap003myfirsttest.examples.naming; import org.junit.Test; import static org.junit.Assert.assertTrue; public class NameClassTest { - @Test public void whenClassHasTestAtEndThenTestIsRun(){ // this test will run from maven so it needs to pass diff --git a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameTestClass.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameTestClass.java similarity index 85% rename from source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameTestClass.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameTestClass.java index 68fdf05..e9ac975 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/NameTestClass.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/NameTestClass.java @@ -1,11 +1,10 @@ -package com.javafortesters.myfirsttest.examples.naming; +package com.javafortesters.chap003myfirsttest.examples.naming; import org.junit.Test; import static org.junit.Assert.assertTrue; public class NameTestClass { - @Test public void whenClassHasTestInMiddleThenTestIsNotRun(){ // this test will not run from maven so i can make diff --git a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/TestNameClass.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/TestNameClass.java similarity index 83% rename from source/src/test/java/com/javafortesters/myfirsttest/examples/naming/TestNameClass.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/TestNameClass.java index 48ae6ed..aeec698 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/examples/naming/TestNameClass.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/examples/naming/TestNameClass.java @@ -1,11 +1,10 @@ -package com.javafortesters.myfirsttest.examples.naming; +package com.javafortesters.chap003myfirsttest.examples.naming; import org.junit.Test; import static org.junit.Assert.assertTrue; public class TestNameClass { - @Test public void whenClassHasTestAtFrontThenTestIsRun(){ // this test will run from maven so it needs to pass diff --git a/source/src/test/java/com/javafortesters/myfirsttest/exercises/MyFirstTestExercisesTest.java b/source/src/test/java/com/javafortesters/chap003myfirsttest/exercises/MyFirstTestExercisesTest.java similarity index 91% rename from source/src/test/java/com/javafortesters/myfirsttest/exercises/MyFirstTestExercisesTest.java rename to source/src/test/java/com/javafortesters/chap003myfirsttest/exercises/MyFirstTestExercisesTest.java index 703e94a..138bc6d 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/exercises/MyFirstTestExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap003myfirsttest/exercises/MyFirstTestExercisesTest.java @@ -1,9 +1,10 @@ -package com.javafortesters.myfirsttest.exercises; +package com.javafortesters.chap003myfirsttest.exercises; import org.junit.Test; + import static org.junit.Assert.assertEquals; diff --git a/source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExamplesTest.java b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/IntegerExamplesTest.java similarity index 88% rename from source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExamplesTest.java rename to source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/IntegerExamplesTest.java index d093c40..dd452a1 100644 --- a/source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExamplesTest.java +++ b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/IntegerExamplesTest.java @@ -1,26 +1,20 @@ -package com.javafortesters.testswithotherclasses; +package com.javafortesters.chap004testswithotherclasses.examples; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class IntegerExamplesTest { @Test public void integerExploration(){ - Integer four = new Integer(4); assertEquals("intValue returns int 4", 4, four.intValue()); - Integer five = new Integer("5"); assertEquals("intValue returns int 5", 5, five.intValue()); - Integer six = 6; assertEquals("autoboxing assignment for 6", 6, six.intValue()); } - - -} \ No newline at end of file +} diff --git a/source/src/test/java/com/javafortesters/testswithotherclasses/interim/IntegerExamplesTest.java b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/interim/IntegerExamplesTest.java similarity index 61% rename from source/src/test/java/com/javafortesters/testswithotherclasses/interim/IntegerExamplesTest.java rename to source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/interim/IntegerExamplesTest.java index 78e7a88..4ac480d 100644 --- a/source/src/test/java/com/javafortesters/testswithotherclasses/interim/IntegerExamplesTest.java +++ b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/interim/IntegerExamplesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.testswithotherclasses.interim; +package com.javafortesters.chap004testswithotherclasses.examples.interim; import org.junit.Test; public class IntegerExamplesTest { diff --git a/source/src/test/java/com/javafortesters/testswithotherclasses/warning/WarningsForIntegerTest.java b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/warning/WarningsForIntegerTest.java similarity index 90% rename from source/src/test/java/com/javafortesters/testswithotherclasses/warning/WarningsForIntegerTest.java rename to source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/warning/WarningsForIntegerTest.java index 78a77c3..87b1e46 100644 --- a/source/src/test/java/com/javafortesters/testswithotherclasses/warning/WarningsForIntegerTest.java +++ b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/examples/warning/WarningsForIntegerTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.testswithotherclasses.warning; +package com.javafortesters.chap004testswithotherclasses.examples.warning; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExercisesTest.java b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/exercises/IntegerExercisesTest.java similarity index 77% rename from source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExercisesTest.java rename to source/src/test/java/com/javafortesters/chap004testswithotherclasses/exercises/IntegerExercisesTest.java index f73fac7..d43e721 100644 --- a/source/src/test/java/com/javafortesters/testswithotherclasses/IntegerExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap004testswithotherclasses/exercises/IntegerExercisesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.testswithotherclasses; +package com.javafortesters.chap004testswithotherclasses.exercises; import org.junit.Test; @@ -20,11 +20,11 @@ public void canConfirmIntMinAndMaxLimits(){ public void canConvertIntToHex(){ assertEquals("hex 11 is b", "b", Integer.toHexString(11)); - assertEquals("hex 10 is b", "a", + assertEquals("hex 10 is a", "a", Integer.toHexString(10)); - assertEquals("hex 3 is b", "3", + assertEquals("hex 3 is 3", "3", Integer.toHexString(3)); - assertEquals("hex 21 is b", "15", + assertEquals("hex 21 is 15", "15", Integer.toHexString(21)); } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/TestAppEnvironmentTest.java b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/TestAppEnvironmentTest.java similarity index 80% rename from source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/TestAppEnvironmentTest.java rename to source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/TestAppEnvironmentTest.java index 7443cf4..6a8f64a 100644 --- a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/TestAppEnvironmentTest.java +++ b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/TestAppEnvironmentTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.testwithourownclasses.domainobject; +package com.javafortesters.chap005testwithourownclasses.domainobject.examples; import com.javafortesters.domainobject.TestAppEnv; import org.junit.Test; @@ -8,9 +8,11 @@ public class TestAppEnvironmentTest { @Test public void canGetUrlStatically(){ + assertEquals("Returns Hard Coded URL", "http://192.123.0.3:67", - TestAppEnv.getUrl()); + TestAppEnv.getUrl() + ); } @Test diff --git a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/interim/TestAppEnvironmentTest.java b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/interim/TestAppEnvironmentTest.java similarity index 50% rename from source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/interim/TestAppEnvironmentTest.java rename to source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/interim/TestAppEnvironmentTest.java index 3319dd8..f8bb45b 100644 --- a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/interim/TestAppEnvironmentTest.java +++ b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/examples/interim/TestAppEnvironmentTest.java @@ -1,12 +1,12 @@ /* -package com.javafortesters.testwithourownclasses.domainobject; +package com.javafortesters.chap005testwithourownclasses.domainobject.examples; public class TestAppEnvironmentTest { } */ -package com.javafortesters.testwithourownclasses.domainobject.interim; +package com.javafortesters.chap005testwithourownclasses.domainobject.examples.interim; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java similarity index 92% rename from source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java rename to source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java index e516f0f..ae5fe62 100644 --- a/source/src/test/java/com/javafortesters/testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java +++ b/source/src/test/java/com/javafortesters/chap005testwithourownclasses/domainobject/exercises/TestAppEnvironmentNoStaticImportTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.testwithourownclasses.domainobject.exercises; +package com.javafortesters.chap005testwithourownclasses.domainobject.exercises; import com.javafortesters.domainobject.TestAppEnv; import org.junit.Assert; diff --git a/source/src/test/java/com/javafortesters/UserTest.java b/source/src/test/java/com/javafortesters/chap006domainentities/examples/UserTest.java similarity index 90% rename from source/src/test/java/com/javafortesters/UserTest.java rename to source/src/test/java/com/javafortesters/chap006domainentities/examples/UserTest.java index c0dd6ec..5a14d99 100644 --- a/source/src/test/java/com/javafortesters/UserTest.java +++ b/source/src/test/java/com/javafortesters/chap006domainentities/examples/UserTest.java @@ -1,13 +1,11 @@ /* -package com.javafortesters.domainentities; - -import org.junit.Test; +package com.javafortesters.chap006domainentities.examples; public class UserTest { } */ -package com.javafortesters; +package com.javafortesters.chap006domainentities.examples; import com.javafortesters.domainentities.User; import org.junit.Test; @@ -23,7 +21,9 @@ public void canConstructANewUser(){ @Test public void userHasDefaultUsernameAndPassword(){ + User user = new User(); + assertEquals("default username expected", "username", user.getUsername()); @@ -31,12 +31,13 @@ public void userHasDefaultUsernameAndPassword(){ assertEquals("default password expected", "password", user.getPassword()); - } @Test public void canConstructWithUsernameAndPassword(){ + User user = new User("admin", "pA55w0rD"); + assertEquals("given username expected", "admin", user.getUsername()); @@ -48,7 +49,9 @@ public void canConstructWithUsernameAndPassword(){ @Test public void canSetPasswordAfterConstructed(){ + User user = new User(); + user.setPassword("PaZZwor6"); assertEquals("setter password expected", diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/differentpackage/UserTest.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/differentpackage/UserTest.java new file mode 100644 index 0000000..2621661 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/differentpackage/UserTest.java @@ -0,0 +1,20 @@ +package com.javafortesters.chap006domainentities.exercises.differentpackage; + +import com.javafortesters.domainentities.User; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class UserTest { + + @Test + public void canConstructWithUsernameAndPassword(){ + User user = new User("admin", "pA55w0rD"); + assertEquals("given username expected", + "admin", + user.getUsername()); + + assertEquals("given password expected", + "pA55w0rD", + user.getPassword()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/User.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/User.java new file mode 100644 index 0000000..f2afac9 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/User.java @@ -0,0 +1,25 @@ +package com.javafortesters.chap006domainentities.exercises.nothiserror; + +/** + * This User, used for exercises only has incorrect constructor code + */ +public class User { + + private String username; + private String password; + + // missing the `this.` so it will fail + // the username being set is not the field, it is the parameter + public User(String username, String password) { + username = username; + password = password; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/UserTest.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/UserTest.java new file mode 100644 index 0000000..8e1cbc1 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothiserror/UserTest.java @@ -0,0 +1,21 @@ +package com.javafortesters.chap006domainentities.exercises.nothiserror; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class UserTest { + + + @Test(expected=AssertionError.class) + public void canConstructWithUsernameAndPassword(){ + User user = new User("admin", "pA55w0rD"); + assertEquals("given username expected", + "admin", + user.getUsername()); + + assertEquals("given password expected", + "pA55w0rD", + user.getPassword()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/User.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/User.java new file mode 100644 index 0000000..41a5e8f --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/User.java @@ -0,0 +1,25 @@ +package com.javafortesters.chap006domainentities.exercises.nothisnoerror; + +/** + * This User, used for exercises only has correct constructor code + */ +public class User { + + private String username; + private String password; + + // missing the `this.` but will not fail + // because of renamed params + public User(String aUsername, String aPassword) { + username = aUsername; + password = aPassword; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/UserTest.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/UserTest.java new file mode 100644 index 0000000..2a955e9 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/nothisnoerror/UserTest.java @@ -0,0 +1,20 @@ +package com.javafortesters.chap006domainentities.exercises.nothisnoerror; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class UserTest { + + + @Test + public void canConstructWithUsernameAndPassword(){ + User user = new User("admin", "pA55w0rD"); + assertEquals("given username expected", + "admin", + user.getUsername()); + + assertEquals("given password expected", + "pA55w0rD", + user.getPassword()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/User.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/User.java new file mode 100644 index 0000000..08f4d47 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/User.java @@ -0,0 +1,12 @@ +package com.javafortesters.chap006domainentities.exercises.publicfields; + + +public class User { + public String username; + public String password; + + public User(){ + username = "admin"; + password = "pA55w0rD"; + } +} diff --git a/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/UserTest.java b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/UserTest.java new file mode 100644 index 0000000..8d190e3 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap006domainentities/exercises/publicfields/UserTest.java @@ -0,0 +1,27 @@ +package com.javafortesters.chap006domainentities.exercises.publicfields; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class UserTest { + + @Test + public void canConstructWithUsernameAndPassword(){ + User auser = new User(); + auser.username = "bob"; + assertEquals("not default username", + "bob", + auser.username); + } + + @Test + public void canSetNameToInvalidValue(){ + User auser = new User(); + auser.username = "12345£$%$"; + assertEquals("invalid username", + "12345£$%$", + auser.username); + } + +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExample.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExample.java similarity index 89% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExample.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExample.java index 9eaa3b3..ad202ab 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExample.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExample.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; public class ClassExample { diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExampleTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExampleTest.java similarity index 94% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExampleTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExampleTest.java index 4c0110d..d418f2a 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ClassExampleTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ClassExampleTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/CommentsTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/CommentsTest.java similarity index 93% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/CommentsTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/CommentsTest.java index 83b69dd..7936879 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/CommentsTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/CommentsTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/DataTypesTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/DataTypesTest.java similarity index 97% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/DataTypesTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/DataTypesTest.java index 88090b4..d9484ae 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/DataTypesTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/DataTypesTest.java @@ -1,4 +1,4 @@ - package com.javafortesters.basicsofjavarevisited; + package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ImportTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ImportTest.java similarity index 84% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/ImportTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ImportTest.java index 0869f40..20178f3 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/ImportTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/ImportTest.java @@ -1,6 +1,6 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; -import com.javafortesters.classes.*; +import com.javafortesters.chap001basicsofjava.examples.classes.*; import com.javafortesters.domainentities.User; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/OperatorsTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/OperatorsTest.java similarity index 96% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/OperatorsTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/OperatorsTest.java index 4457f51..ea29a89 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/OperatorsTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/OperatorsTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; @@ -36,7 +36,7 @@ public void assignmentOperatorsExplored(){ assertEquals("*= multiplies by", 16, num); num /= 4; - assertEquals("*= multiplies by", 4, num); + assertEquals("/= divides by", 4, num); num %=3; assertEquals("%= modulus of", 1, num); diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/StatementsTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StatementsTest.java similarity index 65% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/StatementsTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StatementsTest.java index f3947cb..26a9df0 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/StatementsTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StatementsTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; @@ -12,8 +12,8 @@ public void statements(){ assertEquals(4, 2+2); assertEquals("2+2 always = 4", - 4, - 2+2); + 4, + 2+2); } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/StringsExampleTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StringsExampleTest.java similarity index 91% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/StringsExampleTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StringsExampleTest.java index f737c82..027fb39 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/StringsExampleTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/StringsExampleTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/basicsofjavarevisited/VariablesTest.java b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/VariablesTest.java similarity index 88% rename from source/src/test/java/com/javafortesters/basicsofjavarevisited/VariablesTest.java rename to source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/VariablesTest.java index 81ad27f..11af5d4 100644 --- a/source/src/test/java/com/javafortesters/basicsofjavarevisited/VariablesTest.java +++ b/source/src/test/java/com/javafortesters/chap007basicsofjavarevisited/examples/VariablesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.basicsofjavarevisited; +package com.javafortesters.chap007basicsofjavarevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/selectiondecisions/SelectionTests.java b/source/src/test/java/com/javafortesters/chap008selectiondecisions/examples/SelectionTests.java similarity index 98% rename from source/src/test/java/com/javafortesters/selectiondecisions/SelectionTests.java rename to source/src/test/java/com/javafortesters/chap008selectiondecisions/examples/SelectionTests.java index 4bf7e69..d3238f7 100644 --- a/source/src/test/java/com/javafortesters/selectiondecisions/SelectionTests.java +++ b/source/src/test/java/com/javafortesters/chap008selectiondecisions/examples/SelectionTests.java @@ -1,4 +1,4 @@ -package com.javafortesters.selectiondecisions; +package com.javafortesters.chap008selectiondecisions.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/chap008selectiondecisions/exercises/SelectionExercisesTest.java b/source/src/test/java/com/javafortesters/chap008selectiondecisions/exercises/SelectionExercisesTest.java new file mode 100644 index 0000000..aeee998 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap008selectiondecisions/exercises/SelectionExercisesTest.java @@ -0,0 +1,247 @@ +package com.javafortesters.chap008selectiondecisions.exercises; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class SelectionExercisesTest { + + @Test + public void catOrCats(){ + + int numberOfCats = 1; + + assertEquals("1 == cat", + "cat", + (numberOfCats == 1) ? "cat" : "cats"); + + numberOfCats = 0; + assertEquals("0 == cats", + "cats", + (numberOfCats == 1) ? "cat" : "cats"); + + numberOfCats = 2; + assertEquals("2 == cats", + "cats", + (numberOfCats == 1) ? "cat" : "cats"); + } + + + @Test + public void catOrCatsAsMethod(){ + + assertEquals("1 == cat", "cat", catOrCats(1)); + + assertEquals("0 == cats", "cats", catOrCats(0)); + + assertEquals("2 == cats", "cats", catOrCats(2)); + } + + private String catOrCats(int numberOfCats){ + return (numberOfCats == 1) ? "cat" : "cats"; + } + + @Test + public void truthyIf(){ + boolean truthy=true; + + if(truthy) + assertTrue(truthy); + + if(truthy){ + assertTrue(truthy); + assertFalse(!truthy); + } + } + + @Test + public void truthyIfElse(){ + boolean truthy=true; + + if(truthy) + assertTrue(truthy); + else + assertFalse(truthy); + } + + @Test + public void truthyIfElseBraces(){ + boolean truthy=true; + + if(truthy){ + assertTrue(truthy); + assertFalse(!truthy); + }else{ + assertFalse(truthy); + } + } + + @Test + public void truthyIfElseOnlyOneSetOfBraces(){ + boolean truthy=true; + + if(truthy){ + assertTrue(truthy); + assertFalse(!truthy); + }else + assertFalse(truthy); + } + + @Test + public void nestedIfElseHorror(){ + horrorOfNestedIfElse(true, true); + horrorOfNestedIfElse(true, false); + horrorOfNestedIfElse(false, true); + horrorOfNestedIfElse(false, false); + } + + public void horrorOfNestedIfElse(boolean truthy, boolean falsey){ + + if(truthy){ + if(!falsey){ + if(truthy && !falsey){ + if(falsey || truthy){ + System.out.println("T | F"); + assertTrue(truthy); + assertFalse(falsey); + } + } + }else{ + System.out.println("T | T"); + assertTrue(truthy); + assertTrue(falsey); + } + }else{ + if(!truthy){ + if(falsey){ + System.out.println("F | T"); + assertTrue(falsey); + assertFalse(truthy); + }else{ + System.out.println("F | F"); + assertFalse(falsey); + assertFalse(truthy); + } + } + } + } + + @Test + public void countrySwitch(){ + + assertEquals("United Kingdom", countryOf("UK")); + assertEquals("United States", countryOf("US")); + assertEquals("United States", countryOf("USA")); + assertEquals("United States", countryOf("UsA")); + assertEquals("France", countryOf("FR")); + assertEquals("Sweden", countryOf("sE")); + assertEquals("Rest Of World", countryOf("ES")); + assertEquals("Rest Of World", countryOf("CH")); + } + + private String countryOf(String shortCode) { + + String country; + + switch(shortCode.toUpperCase()){ + case "UK": + country= "United Kingdom"; + break; + case "US": + case "USA": + country = "United States"; + break; + case "FR": + country = "France"; + break; + case "SE": + country = "Sweden"; + break; + default: + country = "Rest Of World"; + break; + } + + return country; + } + + + @Test + public void integerSwitch(){ + + assertEquals("One", integerString(1)); + assertEquals("Two", integerString(2)); + assertEquals("Three", integerString(3)); + assertEquals("Four", integerString(4)); + assertEquals("Too big", integerString(5)); + assertEquals("Too big", integerString(Integer.MAX_VALUE)); + assertEquals("Too small", integerString(0)); + assertEquals("Too small", integerString(Integer.MIN_VALUE)); + } + + private String integerString(int anInt) { + + String valReturn=""; + + switch(anInt){ + case 1: + valReturn = "One"; + break; + case 2: + valReturn = "Two"; + break; + case 3: + valReturn = "Three"; + break; + case 4: + valReturn = "Four"; + break; + default: + if(anInt < 1){ + valReturn = "Too small"; + } + if(anInt > 4){ + valReturn = "Too big"; + } + break; + } + + return valReturn; + } + + + @Test + public void integerSwitchReturnOnly(){ + + assertEquals("One", integerStringUsingReturnOnly(1)); + assertEquals("Two", integerStringUsingReturnOnly(2)); + assertEquals("Three", integerStringUsingReturnOnly(3)); + assertEquals("Four", integerStringUsingReturnOnly(4)); + assertEquals("Too big", integerStringUsingReturnOnly(5)); + assertEquals("Too big", integerStringUsingReturnOnly(Integer.MAX_VALUE)); + assertEquals("Too small", integerStringUsingReturnOnly(0)); + assertEquals("Too small", integerStringUsingReturnOnly(Integer.MIN_VALUE)); + } + + private String integerStringUsingReturnOnly(int anInt) { + switch(anInt){ + case 1: + return "One"; + case 2: + return "Two"; + case 3: + return "Three"; + case 4: + return "Four"; + default: + if(anInt < 1){ + return "Too small"; + } + if(anInt > 4){ + return "Too big"; + } + } + + return ""; + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/arraysiteration/ArrayExampleTest.java b/source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArrayExampleTest.java similarity index 70% rename from source/src/test/java/com/javafortesters/arraysiteration/ArrayExampleTest.java rename to source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArrayExampleTest.java index 96405ec..5c932e5 100644 --- a/source/src/test/java/com/javafortesters/arraysiteration/ArrayExampleTest.java +++ b/source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArrayExampleTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.arraysiteration; +package com.javafortesters.chap009arraysiteration.examples; import org.junit.Test; @@ -11,15 +11,35 @@ public class ArrayExampleTest { @Test - public void arraInitialization(){ + public void simpleArrayExample(){ + String[] numbers0123 = {"zero", "one", "two", "three"}; + + for(String numberText : numbers0123){ + System.out.println(numberText); + } + + assertEquals("zero", numbers0123[0]); + assertEquals("three", numbers0123[3]); + } + + @Test + public void arrayInitialization(){ int[] integers = new int[10]; + int []moreInts = new int[10]; + int evenMore[] = new int[10]; + String strings[] = new String[10]; + int[] zeroLength = {}; + int[] moreZeroLength = new int[0]; + + int[] ints1to10 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + int[] uninitializedArray; - int []zeroLength = {}; - int []moreZeroLength = new int[0]; + uninitializedArray = new int[10]; - int []uninitializedArray; + uninitializedArray = new int[] {100, 200, 300}; strings = new String[] {"mr", "mrs", "sir", "lord", "madam"}; } @@ -46,6 +66,19 @@ public void forLoopWithFixedCondition(){ assertEquals("|Monday|Tuesday|Wednesday|Thursday|Friday",days); } + @Test + public void forLoopUsingIndexFixedCondition(){ + String days=""; + + for(int i=0; i<5; i++){ + days = days + "|" + i + "-" + workdays[i]; + } + + assertEquals( + "|0-Monday|1-Tuesday|2-Wednesday|3-Thursday|4-Friday", + days); + } + @Test public void forLoopMissingInitialization(){ String days=""; diff --git a/source/src/test/java/com/javafortesters/arraysiteration/ArraysClassTest.java b/source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArraysClassTest.java similarity index 91% rename from source/src/test/java/com/javafortesters/arraysiteration/ArraysClassTest.java rename to source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArraysClassTest.java index fe28d99..c1306dc 100644 --- a/source/src/test/java/com/javafortesters/arraysiteration/ArraysClassTest.java +++ b/source/src/test/java/com/javafortesters/chap009arraysiteration/examples/ArraysClassTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.arraysiteration; +package com.javafortesters.chap009arraysiteration.examples; import org.junit.Test; @@ -26,7 +26,7 @@ public void sortArrayOfString(){ @Test public void sortArrayOfInt(){ - int[] outOfOrder = {9,7,8,2,4,3,6,1,5,0}; + int[] outOfOrder = {2,4,3,1,5,0}; Arrays.sort(outOfOrder); @@ -36,10 +36,6 @@ public void sortArrayOfInt(){ assertEquals(3, outOfOrder[3]); assertEquals(4, outOfOrder[4]); assertEquals(5, outOfOrder[5]); - assertEquals(6, outOfOrder[6]); - assertEquals(7, outOfOrder[7]); - assertEquals(8, outOfOrder[8]); - assertEquals(9, outOfOrder[9]); for(int i=0; i numbers0123 = Arrays.asList(numbers0123Array); + + for(String numberText : numbers0123){ + System.out.println(numberText); + } + + assertEquals("zero", numbers0123.get(0)); + assertEquals("three", numbers0123.get(3)); + } + + @Test + public void simpleDynamicCollectionExample(){ + List numbers0123 = new ArrayList(); + + numbers0123.add("zero"); + numbers0123.add("one"); + numbers0123.add("two"); + numbers0123.add("three"); + + for(String numberText : numbers0123){ + System.out.println(numberText); + } + + assertEquals("zero", numbers0123.get(0)); + assertEquals("three", numbers0123.get(3)); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/collections/CollectionInterfacesTest.java b/source/src/test/java/com/javafortesters/chap010collections/examples/CollectionInterfacesTest.java similarity index 99% rename from source/src/test/java/com/javafortesters/collections/CollectionInterfacesTest.java rename to source/src/test/java/com/javafortesters/chap010collections/examples/CollectionInterfacesTest.java index b945b27..be00262 100644 --- a/source/src/test/java/com/javafortesters/collections/CollectionInterfacesTest.java +++ b/source/src/test/java/com/javafortesters/chap010collections/examples/CollectionInterfacesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap010collections.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/collections/IterationWithForAndWhileTest.java b/source/src/test/java/com/javafortesters/chap010collections/examples/IterationWithForAndWhileTest.java similarity index 72% rename from source/src/test/java/com/javafortesters/collections/IterationWithForAndWhileTest.java rename to source/src/test/java/com/javafortesters/chap010collections/examples/IterationWithForAndWhileTest.java index 599475f..e6eae22 100644 --- a/source/src/test/java/com/javafortesters/collections/IterationWithForAndWhileTest.java +++ b/source/src/test/java/com/javafortesters/chap010collections/examples/IterationWithForAndWhileTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap010collections.examples; import org.junit.Test; @@ -53,19 +53,5 @@ public void findMondayWithLoops(){ } - @Test - public void useAForLoopInsteadOfAWhile(){ - - String[] someDays = {"Tuesday","Thursday", - "Wednesday","Monday", - "Saturday","Sunday", - "Friday"}; - List days = Arrays.asList(someDays); - - int forwhile; - for(forwhile=0; !days.get(forwhile).equals("Monday"); forwhile++){ - } - assertEquals("Monday is at position 3", 3, forwhile); - } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/collections/ListInterfaceTest.java b/source/src/test/java/com/javafortesters/chap010collections/examples/ListInterfaceTest.java similarity index 98% rename from source/src/test/java/com/javafortesters/collections/ListInterfaceTest.java rename to source/src/test/java/com/javafortesters/chap010collections/examples/ListInterfaceTest.java index d0d910a..2d20309 100644 --- a/source/src/test/java/com/javafortesters/collections/ListInterfaceTest.java +++ b/source/src/test/java/com/javafortesters/chap010collections/examples/ListInterfaceTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap010collections.examples; import org.junit.Test; @@ -7,7 +7,6 @@ import java.util.List; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; public class ListInterfaceTest { diff --git a/source/src/test/java/com/javafortesters/collections/MapTest.java b/source/src/test/java/com/javafortesters/chap010collections/examples/MapTest.java similarity index 98% rename from source/src/test/java/com/javafortesters/collections/MapTest.java rename to source/src/test/java/com/javafortesters/chap010collections/examples/MapTest.java index d57fb5c..5aae72f 100644 --- a/source/src/test/java/com/javafortesters/collections/MapTest.java +++ b/source/src/test/java/com/javafortesters/chap010collections/examples/MapTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap010collections.examples; import com.javafortesters.domainentities.User; diff --git a/source/src/test/java/com/javafortesters/collections/SetTest.java b/source/src/test/java/com/javafortesters/chap010collections/examples/SetTest.java similarity index 92% rename from source/src/test/java/com/javafortesters/collections/SetTest.java rename to source/src/test/java/com/javafortesters/chap010collections/examples/SetTest.java index ddd33c8..ecffcc3 100644 --- a/source/src/test/java/com/javafortesters/collections/SetTest.java +++ b/source/src/test/java/com/javafortesters/chap010collections/examples/SetTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap010collections.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/chap010collections/exercises/CollectionsExercisesTest.java b/source/src/test/java/com/javafortesters/chap010collections/exercises/CollectionsExercisesTest.java new file mode 100644 index 0000000..56743dd --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap010collections/exercises/CollectionsExercisesTest.java @@ -0,0 +1,121 @@ +package com.javafortesters.chap010collections.exercises; + +import com.javafortesters.domainentities.User; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class CollectionsExercisesTest { + + + + @Test + public void useAForLoopInsteadOfAWhile(){ + + String[] someDays = {"Tuesday","Thursday", + "Wednesday","Monday", + "Saturday","Sunday", + "Friday"}; + + List days = Arrays.asList(someDays); + + int forwhile; + for(forwhile=0; !days.get(forwhile).equals("Monday"); forwhile++){ + } + assertEquals("Monday is at position 3", 3, forwhile); + } + + + @Test + public void createAndManipulateACollectionOfUsers(){ + Collection someUsers = new ArrayList(); + + User bob = new User("bob", "Passw0rd"); + User eris = new User("eris", "Cha0sTime"); + + assertEquals(0, someUsers.size()); + assertTrue(someUsers.isEmpty()); + + someUsers.add(bob); + someUsers.add(eris); + + assertEquals(2, someUsers.size()); + assertFalse(someUsers.isEmpty()); + + Collection secondUsers = new ArrayList(); + User robert = new User("robert", "9assword"); + User aleister = new User("aleister", "Pass5word"); + secondUsers.add(robert); + secondUsers.add(aleister); + assertEquals(2, secondUsers.size()); + + someUsers.addAll(secondUsers); + assertEquals(4, someUsers.size()); + assertTrue(someUsers.containsAll(someUsers)); + assertTrue(someUsers.contains(aleister)); + + secondUsers.removeAll(someUsers); + assertEquals(0, secondUsers.size()); + + someUsers.clear(); + assertEquals(0, someUsers.size()); + } + + + @Test + public void createAndManipulateAListOfUsers(){ + List someUsers = new ArrayList(); + + assertEquals(0, someUsers.size()); + + User bob = new User("bob", "Passw0rd"); + User eris = new User("eris", "Cha0sTime"); + + someUsers.add(bob); + assertEquals(1, someUsers.size()); + + someUsers.add(0, eris); + assertEquals(2, someUsers.size()); + + assertEquals(1, someUsers.indexOf(bob)); + assertEquals(0, someUsers.indexOf(eris)); + + someUsers.remove(0); + assertEquals(0, someUsers.indexOf(bob)); + assertEquals(1, someUsers.size()); + } + + @Test + public void createAndManipulateASetOfUsers(){ + Set someUsers = new HashSet(); + + assertEquals(0, someUsers.size()); + + User bob = new User("bob", "Passw0rd"); + + someUsers.add(bob); + assertEquals(1, someUsers.size()); + + someUsers.add(bob); + assertEquals(1, someUsers.size()); + } + + + @Test + public void createAndManipulateAMapOfUsers(){ + Map someUsers = new HashMap(); + + assertEquals(0, someUsers.size()); + + User bob = new User("bob", "Passw0rd"); + User eris = new User("eris", "Cha0sTime"); + + someUsers.put(bob.getUsername(), bob); + assertEquals(1, someUsers.size()); + + someUsers.put(bob.getUsername(), eris); + assertEquals(1, someUsers.size()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/exceptions/ExceptionsExampleTest.java b/source/src/test/java/com/javafortesters/chap011exceptions/examples/ExceptionsExampleTest.java similarity index 73% rename from source/src/test/java/com/javafortesters/exceptions/ExceptionsExampleTest.java rename to source/src/test/java/com/javafortesters/chap011exceptions/examples/ExceptionsExampleTest.java index 2b48976..0aa4083 100644 --- a/source/src/test/java/com/javafortesters/exceptions/ExceptionsExampleTest.java +++ b/source/src/test/java/com/javafortesters/chap011exceptions/examples/ExceptionsExampleTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.exceptions; +package com.javafortesters.chap011exceptions.examples; import com.javafortesters.domainentities.interim.exceptions.User; import org.junit.Test; @@ -13,13 +13,10 @@ public void throwANullPointerException(){ String ageAsString = age.toString(); - String yourAge = "You are " + - ageAsString + - " years old"; - - assertEquals("You are 18 years old", - yourAge); + String yourAge = + "You are " + ageAsString + " years old"; + assertEquals("You are 18 years old", yourAge); } @@ -36,12 +33,10 @@ public void catchANullPointerException(){ ageAsString = age.toString(); } - String yourAge = "You are " + - age.toString() + - " years old"; + String yourAge = + "You are " + age.toString() + " years old"; - assertEquals("You are 18 years old", - yourAge); + assertEquals("You are 18 years old", yourAge); } @@ -63,12 +58,10 @@ public void catchMultipleExceptions(){ e.getMessage()); } - String yourAge = "You are " + - age.toString() + - " years old"; + String yourAge = + "You are " + age.toString() + " years old"; - assertEquals("You are 18 years old", - yourAge); + assertEquals("You are 18 years old", yourAge); } @Test @@ -103,9 +96,7 @@ public void tryCatchFinallyANullPointerException(){ }finally{ - yourAge = "You are " + - age.toString() + - " years old"; + yourAge = "You are " + age.toString() + " years old"; } assertEquals("You are 18 years old", yourAge); @@ -159,23 +150,6 @@ public void noExceptionThrown(){ new IllegalArgumentException("never thrown"); } - @Test - public void useExceptionAsAnObject(){ - Integer age=null; - String ageAsString; - - try{ - ageAsString = age.toString(); - - }catch(NullPointerException e){ - System.out.println("getMessage - " + - e.getMessage()); - System.out.println("getStacktrace - " + - e.getStackTrace()); - System.out.println("printStackTrace"); - e.printStackTrace(); - } - } @Test (expected = IllegalArgumentException.class) public void passwordMustBeGreaterThan6Chars(){ diff --git a/source/src/test/java/com/javafortesters/chap011exceptions/exercises/IntroducingExceptionsExercisesTest.java b/source/src/test/java/com/javafortesters/chap011exceptions/exercises/IntroducingExceptionsExercisesTest.java new file mode 100644 index 0000000..eab8b71 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap011exceptions/exercises/IntroducingExceptionsExercisesTest.java @@ -0,0 +1,130 @@ +package com.javafortesters.chap011exceptions.exercises; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class IntroducingExceptionsExercisesTest { + + @Test + public void noLongerThrowANullPointerException(){ + Integer age=18; + + String ageAsString = age.toString(); + + String yourAge = + "You are " + ageAsString + " years old"; + + assertEquals("You are 18 years old", yourAge); + } + + @Test(expected = NullPointerException.class) + public void catchADifferentException(){ + + Integer age=null; + String ageAsString; + + try{ + ageAsString = age.toString(); + + }catch(ArithmeticException e){ + age = 18; + ageAsString = age.toString(); + } + + String yourAge = + "You are " + age.toString() + " years old"; + + assertEquals("You are 18 years old", yourAge); + } + + @Test(expected = NullPointerException.class) + public void testNotFixedStillThrowsNullPointer(){ + + Integer age=null; + String ageAsString; + + try{ + ageAsString = age.toString(); + + }catch(ArithmeticException e){ + //age = 18; + ageAsString = age.toString(); + } + + String yourAge = + "You are " + age.toString() + " years old"; + + assertEquals("You are 18 years old", yourAge); + } + + /* + @Test + public void thisTriggersASyntaxErrorBecauseExceptionIsNotDeclared(){ + + Integer age=null; + String ageAsString; + + try{ + ageAsString = age.toString(); + + }catch(NoSuchMethodException e){ + age = 18; + ageAsString = age.toString(); + } + + String yourAge = + "You are " + age.toString() + " years old"; + + assertEquals("You are 18 years old", yourAge); + } + */ + + @Test + public void useExceptionAsAnObject(){ + Integer age=null; + String ageAsString; + + try{ + ageAsString = age.toString(); + + }catch(NullPointerException e){ + System.out.println("getMessage - " + + e.getMessage()); + System.out.println("getStacktrace - " + + e.getStackTrace()); + System.out.println("printStackTrace"); + e.printStackTrace(); + } + } + + @Test + public void useExceptionAsAnObjectExtendedForGetStackTrace(){ + Integer age=null; + String ageAsString; + + try{ + ageAsString = age.toString(); + + }catch(NullPointerException e){ + + System.out.println("getMessage - " + + e.getMessage()); + System.out.println("getStacktrace - " + + e.getStackTrace()); + System.out.println("printStackTrace"); + e.printStackTrace(); + + System.out.println("Stack Trace Length - " + + e.getStackTrace().length); + System.out.println("Stack Trace [0] classname - " + + e.getStackTrace()[0].getClassName()); + System.out.println("Stack Trace [0] filename - " + + e.getStackTrace()[0].getFileName()); + System.out.println("Stack Trace [0] linenumber - " + + e.getStackTrace()[0].getLineNumber()); + System.out.println("Stack Trace [0] methodname - " + + e.getStackTrace()[0].getMethodName()); + } + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap012inheritance/examples/EmptyUser.java b/source/src/test/java/com/javafortesters/chap012inheritance/examples/EmptyUser.java new file mode 100644 index 0000000..0ee6806 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap012inheritance/examples/EmptyUser.java @@ -0,0 +1,6 @@ +package com.javafortesters.chap012inheritance.examples; + +import com.javafortesters.domainentities.User; + +public class EmptyUser extends User { +} diff --git a/source/src/test/java/com/javafortesters/exceptions/InheritanceTest.java b/source/src/test/java/com/javafortesters/chap012inheritance/examples/InheritanceTest.java similarity index 78% rename from source/src/test/java/com/javafortesters/exceptions/InheritanceTest.java rename to source/src/test/java/com/javafortesters/chap012inheritance/examples/InheritanceTest.java index c6e0fed..79fd0ee 100644 --- a/source/src/test/java/com/javafortesters/exceptions/InheritanceTest.java +++ b/source/src/test/java/com/javafortesters/chap012inheritance/examples/InheritanceTest.java @@ -1,16 +1,22 @@ -package com.javafortesters.exceptions; +package com.javafortesters.chap012inheritance.examples; import com.javafortesters.domainentities.AdminUser; import com.javafortesters.domainentities.User; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; public class InheritanceTest { + + @Test + public void emptyUserExampleTest(){ + EmptyUser enu = new EmptyUser(); + assertEquals("username", enu.getUsername()); + assertEquals("password", enu.getPassword()); + } + @Test public void aUserHasNormalPermissions(){ User aUser = new User(); diff --git a/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUser.java b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUser.java new file mode 100644 index 0000000..f384af8 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUser.java @@ -0,0 +1,11 @@ +package com.javafortesters.chap012inheritance.exercises; + +import com.javafortesters.domainentities.User; +import com.javafortesters.domainobject.TestAppEnv; + +public class EnvironmentUser extends User { + + public String getUrl(){ + return TestAppEnv.getUrl(); + } +} diff --git a/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUserTest.java b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUserTest.java new file mode 100644 index 0000000..8ed4188 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/EnvironmentUserTest.java @@ -0,0 +1,16 @@ +package com.javafortesters.chap012inheritance.exercises; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EnvironmentUserTest { + + @Test + public void createAnEnvironmentUser(){ + EnvironmentUser enuser = new EnvironmentUser(); + + assertEquals("username", enuser.getUsername()); + assertEquals("http://192.123.0.3:67", enuser.getUrl()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/myfirsttest/exercises/InheritanceOrCompositionExercisesTest.java b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/InheritanceOrCompositionExercisesTest.java similarity index 66% rename from source/src/test/java/com/javafortesters/myfirsttest/exercises/InheritanceOrCompositionExercisesTest.java rename to source/src/test/java/com/javafortesters/chap012inheritance/exercises/InheritanceOrCompositionExercisesTest.java index 62cf23f..22f0d9f 100644 --- a/source/src/test/java/com/javafortesters/myfirsttest/exercises/InheritanceOrCompositionExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/InheritanceOrCompositionExercisesTest.java @@ -1,24 +1,23 @@ -package com.javafortesters.myfirsttest.exercises; +package com.javafortesters.chap012inheritance.exercises; import com.javafortesters.domainentities.interim.composition.exercises.User; import com.javafortesters.domainentities.interim.composition.exercises.UserStaticComposition; import com.javafortesters.domainobject.TestAppEnv; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; public class InheritanceOrCompositionExercisesTest { @Test public void canComposeUserWithNewTestAppEnv(){ User user = new User(); - assertThat(user.getUrl(), is(TestAppEnv.getUrl())); + assertEquals(user.getUrl(), TestAppEnv.getUrl()); } @Test public void canComposeUserWithStaticTestAppEnv(){ UserStaticComposition user = new UserStaticComposition(); - assertThat(user.getUrl(), is(TestAppEnv.getUrl())); + assertEquals(user.getUrl(), TestAppEnv.getUrl()); } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUser.java b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUser.java new file mode 100644 index 0000000..262583a --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUser.java @@ -0,0 +1,10 @@ +package com.javafortesters.chap012inheritance.exercises; +import com.javafortesters.domainentities.User; + +public class ReadOnlyUser extends User { + + @Override + public String getPermission() { + return "ReadOnly"; + } +} diff --git a/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUserTest.java b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUserTest.java new file mode 100644 index 0000000..15a2143 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap012inheritance/exercises/ReadOnlyUserTest.java @@ -0,0 +1,17 @@ +package com.javafortesters.chap012inheritance.exercises; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ReadOnlyUserTest { + + @Test + public void readOnlyUserPrivsAndDefaults(){ + + ReadOnlyUser rod = new ReadOnlyUser(); + assertEquals("ReadOnly", rod.getPermission()); + assertEquals("username", rod.getUsername()); + assertEquals("password", rod.getPassword()); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/exceptions/customExceptionsTest.java b/source/src/test/java/com/javafortesters/chap013moreexceptions/examples/customExceptionsTest.java similarity index 70% rename from source/src/test/java/com/javafortesters/exceptions/customExceptionsTest.java rename to source/src/test/java/com/javafortesters/chap013moreexceptions/examples/customExceptionsTest.java index 22cc8f5..c500331 100644 --- a/source/src/test/java/com/javafortesters/exceptions/customExceptionsTest.java +++ b/source/src/test/java/com/javafortesters/chap013moreexceptions/examples/customExceptionsTest.java @@ -1,12 +1,12 @@ -package com.javafortesters.exceptions; +package com.javafortesters.chap013moreexceptions.examples; import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; import com.javafortesters.domainentities.interim.exceptions.custom.User; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; public class customExceptionsTest { @@ -20,13 +20,10 @@ public void canCreateDefaultUserWithoutHandlingException(){ @Test public void haveToCatchIllegalPasswordForParamConstructor(){ try { - User aUser = new User("me","letmein"); - + User aUser = new User("me","wrong"); + fail("An exception should have been thrown"); } catch (InvalidPassword invalidPassword) { - - throw new IllegalArgumentException( - "Was not expecting an invalid password exception", - invalidPassword); + assertTrue("The exception was thrown", true); } } diff --git a/source/src/test/java/com/javafortesters/chap013moreexceptions/exercises/CheckedExceptionThrowingUserTest.java b/source/src/test/java/com/javafortesters/chap013moreexceptions/exercises/CheckedExceptionThrowingUserTest.java new file mode 100644 index 0000000..534d217 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap013moreexceptions/exercises/CheckedExceptionThrowingUserTest.java @@ -0,0 +1,51 @@ +package com.javafortesters.chap013moreexceptions.exercises; + +import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; +import com.javafortesters.domainentities.interim.exceptions.custom.User; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class CheckedExceptionThrowingUserTest { + + @Test(expected = InvalidPassword.class) + public void constructUserWithException() throws InvalidPassword { + User aUser = new User("username", "p"); + } + + @Test + public void createDefaultUserWithNoThrowsInvalidPasswordException() { + User aUser = new User(); + assertEquals("password",aUser.getPassword()); + } + + @Test + public void createUserWithInvalidPasswordExceptionMessages(){ + User aUser; + + try { + aUser = new User("username", "p"); + fail("An Invalid Password Exception should have been thrown"); + + } catch (InvalidPassword e) { + assertTrue(e.getMessage().startsWith("Password must be > 6 chars")); + } + } + + @Test + public void setPasswordWithInvalidPasswordExceptionMessages(){ + User aUser = new User(); + + try { + aUser.setPassword("tiny"); + fail("An Invalid Password Exception should have been thrown"); + + } catch (InvalidPassword e) { + assertTrue(e.getMessage().startsWith("Password must be > 6 chars")); + } + } + + +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/junit/JunitExpectedExceptionRuleTest.java b/source/src/test/java/com/javafortesters/chap014junit/examples/JunitExpectedExceptionRuleTest.java similarity index 95% rename from source/src/test/java/com/javafortesters/junit/JunitExpectedExceptionRuleTest.java rename to source/src/test/java/com/javafortesters/chap014junit/examples/JunitExpectedExceptionRuleTest.java index 99584e5..e964aa9 100644 --- a/source/src/test/java/com/javafortesters/junit/JunitExpectedExceptionRuleTest.java +++ b/source/src/test/java/com/javafortesters/chap014junit/examples/JunitExpectedExceptionRuleTest.java @@ -1,8 +1,7 @@ -package com.javafortesters.junit; +package com.javafortesters.chap014junit.examples; import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; import com.javafortesters.domainentities.interim.exceptions.custom.User; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; diff --git a/source/src/test/java/com/javafortesters/chap014junit/examples/JunitReferenceTest.java b/source/src/test/java/com/javafortesters/chap014junit/examples/JunitReferenceTest.java new file mode 100644 index 0000000..45e7911 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap014junit/examples/JunitReferenceTest.java @@ -0,0 +1,66 @@ +package com.javafortesters.chap014junit.examples; + +import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; +import com.javafortesters.domainentities.interim.exceptions.custom.User; +import org.junit.*; + +import java.util.Arrays; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + + +public class JunitReferenceTest { + + @BeforeClass + public static void runOncePerClassBeforeAnyTests(){ + System.out.println("@BeforeClass method"); + } + + @Before + public void runBeforeEveryTestMethod(){ + System.out.println("@Before each method"); + } + + @Test + public void thisTestWillNeverFail(){ + } + + @Test(expected=InvalidPassword.class) + public void expectInvalidPasswordException() throws InvalidPassword { + User user = new User("username", "<6"); + } + + + + @Test(expected=AssertionError.class) + public void junitFailWithDescription(){ + fail("fail always fails"); + } + + @Test(expected=AssertionError.class) + public void junitFailWithoutDescription(){ + fail(); + } + + @Ignore + @Test + public void thisTestIsIgnored(){ + throw new NullPointerException(); + } + + @Ignore("Because it is not finished yet") + @Test + public void thisTestIsIgnoredBecauseItIsNotFinished(){ + } + + @After + public void runAfterEveryTestMethod(){ + System.out.println("@After each method"); + } + + @AfterClass + public static void runOncePerClassAfterAllTests(){ + System.out.println("@AfterClass method"); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap014junit/examples/MyFirstAssertDotTest.java b/source/src/test/java/com/javafortesters/chap014junit/examples/MyFirstAssertDotTest.java new file mode 100644 index 0000000..ed8f8f1 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap014junit/examples/MyFirstAssertDotTest.java @@ -0,0 +1,14 @@ +package com.javafortesters.chap014junit.examples; + +import org.junit.Assert; +import org.junit.Test; + +public class MyFirstAssertDotTest { + + @Test + public void canAddTwoPlusTwo(){ + + int answer = 2+2; + Assert.assertEquals("2+2=4", 4, answer); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/junit/JunitReferenceTest.java b/source/src/test/java/com/javafortesters/chap014junit/exercises/JunitExercisesTest.java similarity index 56% rename from source/src/test/java/com/javafortesters/junit/JunitReferenceTest.java rename to source/src/test/java/com/javafortesters/chap014junit/exercises/JunitExercisesTest.java index edef25e..49c4875 100644 --- a/source/src/test/java/com/javafortesters/junit/JunitReferenceTest.java +++ b/source/src/test/java/com/javafortesters/chap014junit/exercises/JunitExercisesTest.java @@ -1,38 +1,16 @@ -package com.javafortesters.junit; +package com.javafortesters.chap014junit.exercises; + +import org.junit.Test; -import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; -import com.javafortesters.domainentities.interim.exceptions.custom.User; -import org.junit.*; -import org.junit.Assert.*; import java.util.Arrays; import static org.hamcrest.CoreMatchers.*; - +import static org.hamcrest.CoreMatchers.endsWith; +import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.*; -import static org.junit.Assert.assertArrayEquals; - - -public class JunitReferenceTest { - - @BeforeClass - public static void runOncePerClassBeforeAnyTests(){ - System.out.println("@BeforeClass method"); - } - - @Before - public void runBeforeEveryTestMethod(){ - System.out.println("@Before each method"); - } - - @Test - public void thisTestWillNeverFail(){ - } - - @Test(expected=InvalidPassword.class) - public void expectInvalidPasswordException() throws InvalidPassword { - User user = new User("username", "<6"); - } +import static org.junit.Assert.assertThat; +public class JunitExercisesTest { @Test public void junitHasAssertions(){ @@ -68,8 +46,17 @@ public void junitHasAssertions(){ public void assertThatWithHamcrestMatchers(){ assertThat(3 + 3, is(6)); + + /* failing assert used to generate message in book + assertThat(3 + 3, is(7)); + */ + assertThat("3 + 3 = 6", 3 + 3, is(6)); + /* failing assert used to generate message in book + assertThat("3 + 3 = 6", 3 + 3, is(7)); + */ + assertThat("false is false", false, equalTo(false)); assertThat(false, is(false)); @@ -82,7 +69,7 @@ public void assertThatWithHamcrestMatchers(){ assertThat(oneTo10, equalTo(tenToOne)); assertThat("An empty string is not null", "", - is(not(nullValue()))); + is(not(nullValue()))); assertThat("", is(not(nullValue()))); assertThat("",is(notNullValue())); @@ -99,36 +86,6 @@ public void useTheListedHamcrestMatchers(){ assertThat("This is a string", containsString("is")); assertThat("This is a string", endsWith("string")); assertThat("This is a string", startsWith("This is")); - } - - @Test(expected=AssertionError.class) - public void junitFailWithDescription(){ - fail("fail always fails"); - } - - @Test(expected=AssertionError.class) - public void junitFailWithoutDescription(){ - fail(); - } - - @Ignore - @Test - public void thisTestIsIgnored(){ - throw new NullPointerException(); - } - - @Ignore("Because it is not finished yet") - @Test - public void thisTestIsIgnoredBecauseItIsNotFinished(){ } - @After - public void runAfterEveryTestMethod(){ - System.out.println("@After each method"); - } - - @AfterClass - public static void runOncePerClassAfterAllTests(){ - System.out.println("@AfterClass method"); - } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/RegexMatchesTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/RegexMatchesTest.java similarity index 96% rename from source/src/test/java/com/javafortesters/stringsrevisited/RegexMatchesTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/RegexMatchesTest.java index c4ca4da..4069634 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/RegexMatchesTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/RegexMatchesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/StringBuilderTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringBuilderTest.java similarity index 84% rename from source/src/test/java/com/javafortesters/stringsrevisited/StringBuilderTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringBuilderTest.java index 25b75c9..d12b543 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/StringBuilderTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringBuilderTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.examples; import org.junit.Test; @@ -46,13 +46,6 @@ public void appendToStringBuilder(){ assertThat(builder.toString(), is("> 1 + 2 = 3")); } - @Test - public void capacitySizeIncreasesAutomaticallyWithAppend(){ - StringBuilder builder = new StringBuilder(5); - assertThat(builder.capacity(), is(5)); - builder.append("Hello World"); - assertThat(builder.capacity() > 5, is(true)); - } @Test(expected=StringIndexOutOfBoundsException.class) public void insertOutsideIntoStringBuilderWhichIsEmpty(){ @@ -60,20 +53,6 @@ public void insertOutsideIntoStringBuilderWhichIsEmpty(){ builder.insert(5,"Hello"); } - @Test - public void writeATestToInsert(){ - - StringBuilder builder = new StringBuilder(); - builder.insert(0,"a"); - assertThat(builder.toString(), is("a")); - - builder.insert(builder.toString().length(),"b"); - assertThat(builder.toString(), is("ab")); - - builder.insert(1,"."); - assertThat(builder.toString(), is("a.b")); - } - @Test public void insertIntoStringBuilder(){ StringBuilder builder = new StringBuilder("123890"); @@ -86,7 +65,11 @@ public void insertIntoStringBuilder(){ public void insertCharArrayIntoStringBuilder(){ char[] ca = {'.', 'a', 'b', 'c', 'd', 'e', 'f'}; StringBuilder builder = new StringBuilder("abgh"); - builder.insert(2,ca, 3, 4); + // at position 2 in the string + // insert from the char[] ca + // starting at index 3 'c' + // inclusive the next 4 indexes + builder.insert(2, ca, 3, 4); assertThat(builder.toString(), is("abcdefgh")); } diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/StringComparisonsTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringComparisonsTest.java similarity index 73% rename from source/src/test/java/com/javafortesters/stringsrevisited/StringComparisonsTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringComparisonsTest.java index 9153813..ede29bb 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/StringComparisonsTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringComparisonsTest.java @@ -1,10 +1,11 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.examples; -import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; public class StringComparisonsTest { @@ -32,7 +33,7 @@ public void canCheckContainsOnString(){ assertThat(hello.contains("He"), is(true)); assertThat(hello.contains("Hello"), is(true)); - assertThat(hello.contains("he"), is(false)); + assertThat(hello.contains("LL"), is(false)); assertThat(hello.contains("z"), is(false)); assertThat(hello.contains("world"), is(false)); @@ -102,18 +103,35 @@ public void canFindIndexOf(){ public void checkRegionMatches(){ String hello = "Hello fella"; - hello.regionMatches(true, 3,"fez",0,2); - - hello.regionMatches(true, 3,"lady",0,2); - hello.regionMatches(true, 3,"young lady",6,2); - - hello.regionMatches(true, 3,"fel",0,2); + assertThat( + hello.regionMatches(true, 6, "fez", 0, 2), + is(true)); + + // case insensitive search + assertThat( + hello.regionMatches(true, 0, "he", 0, 2), + is(true)); + + // case sensitive search + assertThat( + hello.regionMatches(false, 0, "hE", 0, 2), + is(false)); + assertThat( + hello.regionMatches(0, "hE", 0, 2), + is(false)); + assertThat( + hello.regionMatches(0, "He", 0, 2), + is(true)); + + assertFalse( + hello.regionMatches(true, 3, "lady", 0, 2)); + assertFalse( + hello.regionMatches(true, 3, "young lady", 6, 2)); + + // search for lo + assertTrue( + hello.regionMatches(true, 3, "lololo", 0, 2)); } - @Test - public void exerciseUseRegionMatches(){ - String hello = "Hello fella"; - hello.regionMatches(true, 3,"young lady",6,2); - } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/StringManipulationTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringManipulationTest.java similarity index 97% rename from source/src/test/java/com/javafortesters/stringsrevisited/StringManipulationTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringManipulationTest.java index dd52f65..bbf55c5 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/StringManipulationTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringManipulationTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/StringsRevisitedTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringsRevisitedTest.java similarity index 55% rename from source/src/test/java/com/javafortesters/stringsrevisited/StringsRevisitedTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringsRevisitedTest.java index c7b22c1..78da32c 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/StringsRevisitedTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/examples/StringsRevisitedTest.java @@ -1,9 +1,8 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.examples; import org.junit.Test; import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @@ -29,23 +28,16 @@ public void canUseEscapeSequencesInAString(){ } - @Test - public void tryUsingTheOtherEscapeCharactersOutputToConsole(){ - String firstLine = "|first line\n"; - String secondLine = "|\tsecond line\n"; - String thirdLine = "|\t\tthird line\n"; - String fullLine = firstLine + secondLine + thirdLine; - System.out.println(fullLine); - } - @Test public void canConcatenateStringsInDifferentWays(){ String thisIs = "This is "; String s1 = thisIs.concat("String1"); assertThat(s1, is("This is String1")); - String s2 = thisIs + "String2"; - assertThat(s2, is("This is String2")); + String ps1 = "This is " + "String2"; + assertThat(ps1, is("This is String2")); + String ps2 = "This is " + 4; + assertThat(ps2, is("This is 4")); } @Test @@ -68,30 +60,7 @@ public void canConvertFromStrings(){ assertThat("23".toCharArray(), is(cArray)); } - @Test - public void canConstructStrings(){ - String empty = new String(); - assertThat(empty.length(), is(0)); - - char[] cArray = {'2','3'}; - assertThat(new String(cArray), is("23")); - assertThat(new String(cArray, 1, 1), is("3")); - - byte[] bArray = "hello there".getBytes(); - assertThat(new String(bArray, 3, 3), is("lo ")); - - byte[] b8Array = new byte[0]; - try { - b8Array = "hello there".getBytes("UTF8"); - assertThat(new String(b8Array, 3, 3, "UTF8"), is("lo ")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - String hello = new String("hello" + " " + "there"); - assertThat(hello, is("hello there")); - } @Test diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java similarity index 97% rename from source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java index 6543ccc..7a3ae0d 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesLastIndexOfTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.exercises; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesTest.java similarity index 97% rename from source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesTest.java index e2f0810..c3a5fe4 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/ExerciseStringsRevisitedAllOccurrencesTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/ExerciseStringsRevisitedAllOccurrencesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.exercises; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringBuilderExerciseTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringBuilderExerciseTest.java new file mode 100644 index 0000000..d6fb240 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringBuilderExerciseTest.java @@ -0,0 +1,35 @@ +package com.javafortesters.chap015stringsrevisited.exercises; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +public class StringBuilderExerciseTest { + + @Test + public void capacitySizeIncreasesAutomaticallyWithAppend(){ + StringBuilder builder = new StringBuilder(5); + assertThat(builder.capacity(), is(5)); + builder.append("Hello World"); + assertThat(builder.capacity() > 5, is(true)); + } + + @Test + public void writeATestToInsert(){ + + StringBuilder builder = new StringBuilder(); + + // insert at start + builder.insert(0,"a"); + assertThat(builder.toString(), is("a")); + + // insert to end + builder.insert(builder.toString().length(),"b"); + assertThat(builder.toString(), is("ab")); + + // insert to middle + builder.insert(1,"."); + assertThat(builder.toString(), is("a.b")); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringExercisesTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringExercisesTest.java new file mode 100644 index 0000000..275ef39 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/StringExercisesTest.java @@ -0,0 +1,63 @@ +package com.javafortesters.chap015stringsrevisited.exercises; + +import org.junit.Test; + +import java.io.UnsupportedEncodingException; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class StringExercisesTest { + + @Test + public void tryUsingTheOtherEscapeCharactersOutputToConsole(){ + System.out.println("New lines, and Tabs"); + String firstLine = "|first line\n"; + String secondLine = "|\tsecond line\n"; + String thirdLine = "|\t\tthird line\n"; + String fullLine = firstLine + secondLine + thirdLine; + System.out.println(fullLine); + + System.out.println("Carriage return after each word"); + System.out.println("one\rtwo\rthree\rfour\rfive\r"); + + System.out.println("Backspace after each word"); + System.out.println("one\btwo\bthree\bfour\bfive\b"); + + System.out.println("Quotes and slashes"); + System.out.println("Bob\'s toy said \"DOS uses \'\\\'\""); + } + + @Test + public void canConstructStrings(){ + + String empty = new String(); + assertThat(empty.length(), is(0)); + + char[] cArray = {'2','3'}; + assertThat(new String(cArray), is("23")); + assertThat(new String(cArray, 1, 1), is("3")); + + byte[] bArray = "hello there".getBytes(); + assertThat(new String(bArray, 3, 3), is("lo ")); + + byte[] b8Array = new byte[0]; + try { + b8Array = "hello there".getBytes("UTF8"); + assertThat(new String(b8Array, 3, 3, "UTF8"), is("lo ")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + String hello = new String("hello" + " " + "there"); + assertThat(hello, is("hello there")); + } + + + @Test + public void exerciseUseRegionMatches(){ + String hello = "Hello fella"; + assertTrue(hello.regionMatches(true, 9,"young lady",6,2)); + } +} \ No newline at end of file diff --git a/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/regex/User.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/User.java similarity index 95% rename from source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/regex/User.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/User.java index b249cf3..0c1d275 100644 --- a/source/src/main/java/com/javafortesters/domainentities/interim/exceptions/custom/regex/User.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/User.java @@ -1,4 +1,4 @@ -package com.javafortesters.domainentities.interim.exceptions.custom.regex; +package com.javafortesters.chap015stringsrevisited.exercises; import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; diff --git a/source/src/test/java/com/javafortesters/stringsrevisited/UserPasswordExceptionsTest.java b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/UserPasswordExceptionsTest.java similarity index 61% rename from source/src/test/java/com/javafortesters/stringsrevisited/UserPasswordExceptionsTest.java rename to source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/UserPasswordExceptionsTest.java index 6b0a9c3..a48ec6b 100644 --- a/source/src/test/java/com/javafortesters/stringsrevisited/UserPasswordExceptionsTest.java +++ b/source/src/test/java/com/javafortesters/chap015stringsrevisited/exercises/UserPasswordExceptionsTest.java @@ -1,52 +1,68 @@ -package com.javafortesters.stringsrevisited; +package com.javafortesters.chap015stringsrevisited.exercises; import com.javafortesters.domainentities.interim.exceptions.custom.InvalidPassword; -import com.javafortesters.domainentities.interim.exceptions.custom.regex.User; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; public class UserPasswordExceptionsTest { @Test(expected = InvalidPassword.class) public void passwordMustHaveANumber() throws InvalidPassword { User aUser = new User("username", "Password"); + fail("User creation should have thrown an exception"); } @Test(expected = InvalidPassword.class) public void passwordMustHaveAnUppercase() throws InvalidPassword { User aUser = new User("username", "1assword"); + assertEquals("1assword", aUser.getPassword()); } @Test (expected = InvalidPassword.class) public void passwordMustBeGreaterThan6Chars() throws InvalidPassword { User aUser = new User("username", "I23456"); + assertEquals("I23456", aUser.getPassword()); } @Test public void multipleUppercaseAndDigitsAllowed() throws InvalidPassword { User aUser = new User("username", "I23456T"); + assertEquals("I23456T", aUser.getPassword()); + aUser = new User("username", "12B4S6TP"); + assertEquals("12B4S6TP", aUser.getPassword()); } @Test - public void canStilCreateDefaultUser(){ + public void canStillCreateDefaultUser(){ User aUser = new User(); assertThat(aUser.getPassword(), is("Passw0rd")); } @Test - public void passwordMatches() throws InvalidPassword { + public void validPasswordMatchExamples() throws InvalidPassword { User aUser = new User("username", "Password2"); + assertEquals("Password2", aUser.getPassword()); + aUser = new User("username", "Pas5word"); + assertEquals("Pas5word", aUser.getPassword()); aUser = new User("username", "I1234567"); + assertEquals("I1234567", aUser.getPassword()); + aUser = new User("username", "1234S67"); + assertEquals("1234S67", aUser.getPassword()); + aUser = new User("username", "123456T"); + assertEquals("123456T", aUser.getPassword()); aUser = new User("username", "I1234567ten"); + assertEquals("I1234567ten", aUser.getPassword()); } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap016random/examples/JavaUtilRandomTest.java b/source/src/test/java/com/javafortesters/chap016random/examples/JavaUtilRandomTest.java new file mode 100644 index 0000000..4eeb8b8 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap016random/examples/JavaUtilRandomTest.java @@ -0,0 +1,120 @@ +package com.javafortesters.chap016random.examples; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +public class JavaUtilRandomTest { + + @Test + public void generateRandomSyntaxExamples(){ + Random generate = new Random(); + + // essentially code duplication to + // demonstrate syntax in manuscript + // result checked in the exercise tests + + boolean randomBoolean = generate.nextBoolean(); + int randomInt = generate.nextInt(); + int randomIntRange = generate.nextInt(12); + long randomLong = generate.nextLong(); + double randomDouble = generate.nextDouble(); + double randomGaussian = generate.nextGaussian(); + byte[] bytes = new byte[generate.nextInt(100)]; + generate.nextBytes(bytes); // fill bytes with random data + + Assert.assertNotNull(generate); + } + + + @Test + public void generateRandomIntRange(){ + Random generate = new Random(); + int rir; + + rir = generate.nextInt(5); + assertThat(rir >= 0 && rir < 5, is(true)); + rir = generate.nextInt(200); + assertThat(rir >= 0 && rir < 200, is(true)); + rir = generate.nextInt(4000); + assertThat(rir >= 0 && rir < 4000, is(true)); + } + + + @Test + public void generateRandomIntGivenRangeNot0(){ + Random generate = new Random(); + + int minValue = 1; + int maxValue = 5; + int randomIntRange = generate.nextInt( + maxValue - minValue + 1) + minValue; + + assertThat(randomIntRange<=maxValue, is(true)); + assertThat(randomIntRange >=minValue, is(true)); + } + + + @Test + public void canGenerateAgeUsingDeviation(){ + + Random generate = new Random(); + + + int age = (int)(generate.nextGaussian() * 5) + 35; + + if(age<15) + age=15; + + if(age>55) + age=55; + + // dangerous assertions as the test might fail, + // hence the max and min above + Assert.assertTrue(age>14); + Assert.assertTrue(age<56); + } + + + @Test + public void canGenerateRandomNumbersWithSeedExample(){ + Random generate = new Random(1234567L); + assertThat(generate.nextInt() , is(1042961893)); + } + + @Test + public void canSeedWithCurrentDateTime(){ + long currentSeed = System.currentTimeMillis(); + System.out.println("seed used: " + currentSeed); + Random generate = new Random(currentSeed); + + int prevInt = generate.nextInt(); + System.out.println(generate.nextInt()); + + Random generateAgain = new Random(currentSeed); + assertThat(generateAgain.nextInt() , is(prevInt)); + } + + + @Test + public void generateARandomCharExample(){ + + String validValues = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; + + Random random = new Random(); + + int rndIndex = random.nextInt(validValues.length()); + char rChar = validValues.charAt(rndIndex); + + if(rChar!=' '){ + Assert.assertTrue(rChar>='A'); + Assert.assertTrue(rChar<='Z'); + } + } + + +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/random/MathRandomTest.java b/source/src/test/java/com/javafortesters/chap016random/examples/MathRandomTest.java similarity index 81% rename from source/src/test/java/com/javafortesters/random/MathRandomTest.java rename to source/src/test/java/com/javafortesters/chap016random/examples/MathRandomTest.java index a698a2b..5c8a35d 100644 --- a/source/src/test/java/com/javafortesters/random/MathRandomTest.java +++ b/source/src/test/java/com/javafortesters/chap016random/examples/MathRandomTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.random; +package com.javafortesters.chap016random.examples; import org.junit.Test; @@ -17,7 +17,7 @@ public void canUseRandomMethodOnMath(){ "generated %f as random number", rnd)); assertThat(rnd < 1.0d, is(true)); - assertThat(rnd > 0.0d, is(true)); + assertThat(rnd >= 0.0d, is(true)); } diff --git a/source/src/test/java/com/javafortesters/random/JavaUtilRandomTest.java b/source/src/test/java/com/javafortesters/chap016random/exercises/JavaUtilRandomExercisesTest.java similarity index 66% rename from source/src/test/java/com/javafortesters/random/JavaUtilRandomTest.java rename to source/src/test/java/com/javafortesters/chap016random/exercises/JavaUtilRandomExercisesTest.java index 857effc..09efa0a 100644 --- a/source/src/test/java/com/javafortesters/random/JavaUtilRandomTest.java +++ b/source/src/test/java/com/javafortesters/chap016random/exercises/JavaUtilRandomExercisesTest.java @@ -1,5 +1,6 @@ -package com.javafortesters.random; +package com.javafortesters.chap016random.exercises; +import org.junit.Assert; import org.junit.Test; import java.util.*; @@ -7,43 +8,15 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -public class JavaUtilRandomTest { - - @Test - public void generateRandomNumberWithNoSeed(){ - Random generate = new Random(); - int randomValue = generate.nextInt(); - - assertThat(randomValue=Integer.MIN_VALUE, is(true)); - } - - - @Test - public void canGenerateRandomBoolean(){ - Random generate = new Random(); - int countTrue = 0; - int countFalse = 0; - - for(int x=0; x<1000; x++){ - boolean randomBoolean = generate.nextBoolean(); - - if(randomBoolean){ - countTrue++; - }else{ - countFalse++; - } - System.out.println(randomBoolean); - } - assertThat(countTrue>0, is(true)); - assertThat(countFalse>0, is(true)); - } +public class JavaUtilRandomExercisesTest { + /* Tests which confirm random limits */ @Test public void canGenerateRandomInt(){ Random generate = new Random(); for(int x=0; x<1000; x++){ + int randomInt = generate.nextInt(); System.out.println(randomInt); @@ -53,56 +26,32 @@ public void canGenerateRandomInt(){ } @Test - public void generateRandomIntGivenRange(){ + public void canGenerateRandomBoolean(){ Random generate = new Random(); + int countTrue = 0; + int countFalse = 0; for(int x=0; x<1000; x++){ - int randomIntRange = generate.nextInt(12); - System.out.println(randomIntRange); - assertThat(randomIntRange<12, is(true)); - assertThat(randomIntRange >=0, is(true)); - } - } - - - @Test - public void generateRandomIntRange(){ - Random generate = new Random(); - int rir; - - rir = generate.nextInt(5); - assertThat(rir >= 0 && rir < 5, is(true)); - rir = generate.nextInt(200); - assertThat(rir >= 0 && rir < 200, is(true)); - rir = generate.nextInt(4000); - assertThat(rir >= 0 && rir < 4000, is(true)); - } - - @Test - public void generateRandomIntGivenRangeNot0(){ - Random generate = new Random(); + boolean randomBoolean = generate.nextBoolean(); - Set nums = new HashSet(); + if(randomBoolean) + countTrue++; - for(int x=0; x<1000; x++){ - int minValue = 15; - int maxValue = 20; - int randomIntRange = generate.nextInt( - maxValue - minValue + 1) + minValue; + if(randomBoolean==false) + countFalse++; - nums.add(randomIntRange); - assertThat(randomIntRange<=maxValue, is(true)); - assertThat(randomIntRange >=minValue, is(true)); + System.out.println(randomBoolean); } - assertThat(nums.size(), is(6)); - assertThat(nums.contains(15), is(true)); - assertThat(nums.contains(16), is(true)); - assertThat(nums.contains(17), is(true)); - assertThat(nums.contains(18), is(true)); - assertThat(nums.contains(19), is(true)); - assertThat(nums.contains(20), is(true)); + System.out.println( + String.format("Generated %d as true", countTrue)); + System.out.println( + String.format("Generated %d as false", countFalse)); + + assertThat(countTrue>0, is(true)); + assertThat(countFalse>0, is(true)); + assertThat(countTrue + countFalse, is(1000)); } @Test @@ -111,7 +60,6 @@ public void canGenerateRandomLong(){ for(int x=0; x<1000; x++){ long randomLong = generate.nextLong(); - System.out.println(randomLong); assertThat(randomLong=Long.MIN_VALUE, is(true)); @@ -124,38 +72,79 @@ public void canGenerateRandomFloat(){ for(int x=0; x<1000; x++){ float randomFloat = generate.nextFloat(); - System.out.println(randomFloat); assertThat(randomFloat<1.0f, is(true)); assertThat(randomFloat >=0.0f, is(true)); } } - @Test public void canGenerateRandomDouble(){ Random generate = new Random(); for(int x=0; x<1000; x++){ double randomDouble = generate.nextDouble(); - System.out.println(randomDouble); assertThat(randomDouble<1.0d, is(true)); assertThat(randomDouble >=0.0d, is(true)); } } + @Test public void canGenerateRandomByte(){ Random generate = new Random(); for(int x=0; x<1000; x++){ - byte[] bytes = new byte[generate.nextInt(100)]; + // randomly generate a byte array between 0 and 99 length + int arrayLength = generate.nextInt(100); + byte[] bytes = new byte[arrayLength]; generate.nextBytes(bytes); // fill bytes with random data + Assert.assertEquals(arrayLength, bytes.length); + String viewbytes = new String(bytes); + System.out.println(bytes.length + " - " + viewbytes); + } + } + + + @Test + public void generateRandomIntGivenRange(){ + Random generate = new Random(); + + for(int x=0; x<1000; x++){ + // between 0 (>=) and <(12) + int randomIntRange = generate.nextInt(12); + System.out.println(randomIntRange); + assertThat(randomIntRange<=11, is(true)); + assertThat(randomIntRange >=0, is(true)); + } + } + + @Test + public void generateRandomIntGivenRangeNot0Exercise(){ + Random generate = new Random(); + + Set nums = new HashSet(); + + for(int x=0; x<1000; x++){ + + int minValue = 15; + int maxValue = 20; + int randomIntRange = generate.nextInt( + maxValue - minValue + 1) + minValue; - System.out.println(bytes.length); - System.out.println(new String(bytes)); + nums.add(randomIntRange); + assertThat(randomIntRange<=maxValue, is(true)); + assertThat(randomIntRange >=minValue, is(true)); } + + assertThat(nums.size(), is(6)); + assertThat(nums.contains(15), is(true)); + assertThat(nums.contains(16), is(true)); + assertThat(nums.contains(17), is(true)); + assertThat(nums.contains(18), is(true)); + assertThat(nums.contains(19), is(true)); + assertThat(nums.contains(20), is(true)); } @Test @@ -168,6 +157,7 @@ public void canGenerateRandomGaussianDistributionDouble(){ int standardDeviationCount4 = 0; for(int x=0; x<1000; x++){ + double randomGaussian = generate.nextGaussian(); //System.out.println(randomValue); @@ -186,23 +176,29 @@ public void canGenerateRandomGaussianDistributionDouble(){ float sd1percentage = (standardDeviationCount1/1000f) * 100f; System.out.println("about 70% one standard deviation = " + - sd1percentage); + sd1percentage); float sd2percentage = (standardDeviationCount2/1000f) * 100f; System.out.println("about 95% two standard deviation = " + - sd2percentage); + sd2percentage); float sd3percentage = (standardDeviationCount3/1000f) * 100f; System.out.println("about 99% three standard deviation = " + - sd3percentage); + sd3percentage); float sd4percentage = (standardDeviationCount4/1000f) * 100f; System.out.println("about 99.9% four standard deviation = " + - sd4percentage); + sd4percentage); + + Assert.assertTrue(sd1percentage < sd2percentage); + Assert.assertTrue(sd2percentage < sd3percentage); + // I do not assert that sd3 and sd4 are different + // because of the small % difference, they do overlap } + @Test - public void canGenerateAgeUsingDeviation(){ + public void canGenerate1000AgesUsingDeviation(){ Random generate = new Random(); Map ages = @@ -226,33 +222,20 @@ public void canGenerateAgeUsingDeviation(){ } } - @Test public void canGenerateRandomNumbersWithSeed(){ for(int x=0; x<10; x++){ - Random generate = new Random(1234567L); - - assertThat(generate.nextInt() , is(1042961893)); - assertThat(generate.nextLong() , is(-6749250865724111202L)); - assertThat(generate.nextDouble() , is(0.44762832574617084D)); - assertThat(generate.nextGaussian() , is(-0.11571220872310763D)); - assertThat(generate.nextFloat() , is(0.33144182F)); - assertThat(generate.nextBoolean() , is(false)); - } - } - - @Test - public void canSeedWithCurrentDateTime(){ - long currentSeed = System.currentTimeMillis(); - System.out.println("seed: " + currentSeed); - Random generate = new Random(currentSeed); - int prevInt = generate.nextInt(); - System.out.println(generate.nextInt()); + Random generate = new Random(1234567L); - Random generateAgain = new Random(currentSeed); - assertThat(generateAgain.nextInt() , is(prevInt)); + assertThat(generate.nextInt() , is(1042961893)); + assertThat(generate.nextLong() , is(-6749250865724111202L)); + assertThat(generate.nextDouble() , is(0.44762832574617084D)); + assertThat(generate.nextGaussian() , is(-0.11571220872310763D)); + assertThat(generate.nextFloat() , is(0.33144182F)); + assertThat(generate.nextBoolean() , is(false)); + } } @Test @@ -266,36 +249,13 @@ public void generateARandomString(){ rString = new StringBuilder(); for(int x=0; x<100; x++){ - char rChar = validValues.charAt( - random.nextInt( - validValues.length())); + int rndIndex = random.nextInt(validValues.length()); + char rChar = validValues.charAt(rndIndex); rString.append(rChar); } System.out.println(rString.toString()); + Assert.assertTrue(rString.length()==100); + Assert.assertTrue(rString.toString().matches("[A-Z ]+")); } - - @Test - public void generateRandomString(){ - - String validValues = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; - - StringBuilder rString; - - Random random = new Random(); - - for(int strings=0; strings<1000; strings++){ - rString = new StringBuilder(); - for(int x=0; x<100; x++){ - rString.append( - validValues.charAt( - random.nextInt( - validValues.length()))); - } - - System.out.println(rString.toString()); - } - } - - } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap017_datestimes/examples/CalendarTest.java b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/CalendarTest.java new file mode 100644 index 0000000..db0f353 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/CalendarTest.java @@ -0,0 +1,94 @@ +package com.javafortesters.chap017_datestimes.examples; + +import org.junit.Test; + +import java.util.Calendar; +import java.util.Date; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class CalendarTest { + + @Test + public void calendarExploration(){ + + Calendar cal = Calendar.getInstance(); + + System.out.println(cal.getTime().getTime()); + System.out.println(System.currentTimeMillis()); + + System.out.println(cal.toString()); + + Calendar sameDate = Calendar.getInstance(); + sameDate.setTime(cal.getTime()); + assertThat(cal.equals(sameDate), is(true)); + assertThat(cal.compareTo(sameDate), is(0)); + + System.out.println(cal.getTime().toString()); + Calendar oneWeekFromNow = Calendar.getInstance(); + oneWeekFromNow.setTime(cal.getTime()); + oneWeekFromNow.add(Calendar.DATE,7); + System.out.println(oneWeekFromNow.getTime().toString()); + + assertThat(oneWeekFromNow.after(cal), is(true)); + assertThat(cal.before(oneWeekFromNow), is(true)); + assertThat(cal.compareTo(oneWeekFromNow), is(-1)); + assertThat(oneWeekFromNow.compareTo(cal), is(1)); + } + + @Test + public void setCalendarFields(){ + + Calendar cal = Calendar.getInstance(); + + cal.set(Calendar.YEAR, 2013); + cal.set(Calendar.MONTH, 11); // starts at 0 + cal.set(Calendar.DAY_OF_MONTH, 15); + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 39); + cal.set(Calendar.SECOND, 54); + cal.set(Calendar.MILLISECOND, 123); + + cal.set(Calendar.MONTH, Calendar.DECEMBER); + + System.out.println(cal.getTime().toString()); + + cal.set(2013, 11, 15); + cal.set(2013, Calendar.DECEMBER, 15); + cal.set(2013, 11, 15, 23, 39); + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + + assertThat(cal.get(Calendar.YEAR), is(2013)); + + cal.setTimeInMillis(0L); + assertThat(cal.get(Calendar.YEAR), is(1970)); + + cal.setTime(new Date(0L)); + assertThat(cal.get(Calendar.YEAR), is(1970)); + + cal.setWeekDate(2013, 3, Calendar.THURSDAY); + assertThat(cal.get(Calendar.MONTH), is(Calendar.JANUARY)); + assertThat(cal.get(Calendar.DAY_OF_MONTH), is(17)); + } + + @Test + public void getCalendarDetails(){ + Calendar cal = Calendar.getInstance(); + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + + assertThat(cal.get(Calendar.MONTH), is(Calendar.DECEMBER)); + } + + @Test + public void addDaysToCalendar(){ + Calendar cal = Calendar.getInstance(); + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + + cal.add(Calendar.HOUR_OF_DAY, -1); + assertThat(cal.get(Calendar.HOUR_OF_DAY), is(22)); + + cal.add(Calendar.MINUTE, 10); + assertThat(cal.get(Calendar.MINUTE), is(49)); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/datestimes/DateTest.java b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/DateTest.java similarity index 76% rename from source/src/test/java/com/javafortesters/datestimes/DateTest.java rename to source/src/test/java/com/javafortesters/chap017_datestimes/examples/DateTest.java index 58faf94..91cf8fd 100644 --- a/source/src/test/java/com/javafortesters/datestimes/DateTest.java +++ b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/DateTest.java @@ -1,8 +1,8 @@ -package com.javafortesters.datestimes; +package com.javafortesters.chap017_datestimes.examples; +import org.junit.Assert; import org.junit.Test; -import java.text.DateFormat; import java.util.Date; import static org.hamcrest.CoreMatchers.is; @@ -14,9 +14,18 @@ public class DateTest { public void dateExploration(){ Date date = new Date(); + + Date equivDate1 = new Date(); + Date equivDate2 = new Date(System.currentTimeMillis()); System.out.println(date.getTime()); System.out.println(System.currentTimeMillis()); + Assert.assertEquals(equivDate1, equivDate2); + + + System.out.println(new Date().getTime()); + System.out.println(System.currentTimeMillis()); + System.out.println(date.toString()); long oneWeekFromNowTime = date.getTime(); diff --git a/source/src/test/java/com/javafortesters/datestimes/SimpleDateFormatTest.java b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/SimpleDateFormatTest.java similarity index 98% rename from source/src/test/java/com/javafortesters/datestimes/SimpleDateFormatTest.java rename to source/src/test/java/com/javafortesters/chap017_datestimes/examples/SimpleDateFormatTest.java index eae0e73..f155c3f 100644 --- a/source/src/test/java/com/javafortesters/datestimes/SimpleDateFormatTest.java +++ b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/SimpleDateFormatTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.datestimes; +package com.javafortesters.chap017_datestimes.examples; import org.junit.Test; @@ -113,6 +113,7 @@ public void unusualDateFormatPatterns() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("y M d HH:mm:ss.SSS"); Date date = sdf.parse("2013 12 15 23:39:54.123"); + String[][] formatElement = { {"w", "Week in the year"}, {"www", "Week in the year"}, diff --git a/source/src/test/java/com/javafortesters/chap017_datestimes/examples/TimeTest.java b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/TimeTest.java new file mode 100644 index 0000000..2a476c0 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap017_datestimes/examples/TimeTest.java @@ -0,0 +1,30 @@ +package com.javafortesters.chap017_datestimes.examples; + +import org.junit.Assert; +import org.junit.Test; + +public class TimeTest { + + @Test + public void currentTimeMillis(){ + long startTime = System.currentTimeMillis(); + + for(int x=0; x < 10; x++){ + System.out.println("Current Time " + + System.currentTimeMillis()); + } + + long endTime = System.currentTimeMillis(); + System.out.println("Total Time " + (endTime - startTime)); + } + + @Test + public void createAUniqueUserID(){ + + String userID = "user" + System.currentTimeMillis(); + + System.out.println(userID); + Assert.assertTrue(userID.startsWith("user")); + Assert.assertTrue(Long.valueOf(userID.replace("user",""))>1000L); + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/datestimes/CalendarTest.java b/source/src/test/java/com/javafortesters/chap017_datestimes/exercises/DateTimeExercisesTest.java similarity index 52% rename from source/src/test/java/com/javafortesters/datestimes/CalendarTest.java rename to source/src/test/java/com/javafortesters/chap017_datestimes/exercises/DateTimeExercisesTest.java index a9a63b7..0bdb95f 100644 --- a/source/src/test/java/com/javafortesters/datestimes/CalendarTest.java +++ b/source/src/test/java/com/javafortesters/chap017_datestimes/exercises/DateTimeExercisesTest.java @@ -1,89 +1,67 @@ -package com.javafortesters.datestimes; +package com.javafortesters.chap017_datestimes.exercises; import org.junit.Test; import java.util.Calendar; -import java.util.Date; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class CalendarTest { +public class DateTimeExercisesTest { @Test - public void calendarExploration(){ + public void nanoTime(){ + long startTime = System.nanoTime(); - Calendar cal = Calendar.getInstance(); - - System.out.println(cal.getTime().getTime()); - System.out.println(System.currentTimeMillis()); + for(int x=0; x < 10; x++){ + System.out.println("Current Time " + System.nanoTime()); + } - System.out.println(cal.toString()); - - Calendar sameDate = Calendar.getInstance(); - sameDate.setTime(cal.getTime()); - assertThat(cal.equals(sameDate), is(true)); - assertThat(cal.compareTo(sameDate), is(0)); - - System.out.println(cal.getTime().toString()); - Calendar oneWeekFromNow = Calendar.getInstance(); - oneWeekFromNow.setTime(cal.getTime()); - oneWeekFromNow.add(Calendar.DATE,7); - System.out.println(oneWeekFromNow.getTime().toString()); - - assertThat(oneWeekFromNow.after(cal), is(true)); - assertThat(cal.before(oneWeekFromNow), is(true)); - assertThat(cal.compareTo(oneWeekFromNow), is(-1)); - assertThat(oneWeekFromNow.compareTo(cal), is(1)); + long endTime = System.nanoTime(); + System.out.println("Total Time " + (endTime - startTime)); } @Test - public void writeCalendarToStringToConsole(){ - Calendar cal = Calendar.getInstance(); - System.out.println(cal.toString()); - } + public void createAUniqueUserIDAllChars(){ + String initialUserID = "user" + System.currentTimeMillis(); + System.out.println(initialUserID); - @Test - public void setCalendarFields(){ + String userID = initialUserID; - Calendar cal = Calendar.getInstance(); + for(int x = 0; x< 10; x++){ + String charReplacement = "" + ((char)('A'+x)); + String intToReplace = String.valueOf(x); + userID = userID.replace( intToReplace, charReplacement); + } - cal.set(Calendar.YEAR,2013); - cal.set(Calendar.MONTH, 11); // starts at 0 - cal.set(Calendar.DAY_OF_MONTH,15); - cal.set(Calendar.HOUR_OF_DAY, 23); - cal.set(Calendar.MINUTE,39); - cal.set(Calendar.SECOND, 54); - cal.set(Calendar.MILLISECOND, 123); + assertThat(userID.contains("0"), is(false)); + assertThat(userID.contains("1"), is(false)); + assertThat(userID.contains("2"), is(false)); + assertThat(userID.contains("3"), is(false)); + assertThat(userID.contains("4"), is(false)); + assertThat(userID.contains("5"), is(false)); + assertThat(userID.contains("6"), is(false)); + assertThat(userID.contains("7"), is(false)); + assertThat(userID.contains("8"), is(false)); + assertThat(userID.contains("9"), is(false)); - cal.set(Calendar.MONTH,Calendar.DECEMBER); + assertThat(initialUserID.length(), is(userID.length())); - System.out.println(cal.getTime().toString()); - - cal.set(2013, 11, 15); - cal.set(2013, Calendar.DECEMBER, 15); - cal.set(2013, 11, 15, 23, 39); - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); - - assertThat(cal.get(Calendar.YEAR), is(2013)); - - cal.setTimeInMillis(0L); - assertThat(cal.get(Calendar.YEAR), is(1970)); - - cal.setTime(new Date(0L)); - assertThat(cal.get(Calendar.YEAR), is(1970)); + System.out.println(userID); + } - cal.setWeekDate(2013, 3, Calendar.THURSDAY); - assertThat(cal.get(Calendar.MONTH), is(Calendar.JANUARY)); - assertThat(cal.get(Calendar.DAY_OF_MONTH), is(17)); + @Test + public void writeCalendarToStringToConsole(){ + Calendar cal = Calendar.getInstance(); + System.out.println(cal.toString()); } @Test - public void getCalendarDetails(){ + public void useOtherCalendarConstants(){ Calendar cal = Calendar.getInstance(); - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); assertThat(cal.get(Calendar.MONTH), is(Calendar.DECEMBER)); assertThat(cal.get(Calendar.YEAR), is(2013)); assertThat(cal.get(Calendar.DAY_OF_MONTH), is(15)); @@ -95,47 +73,26 @@ public void getCalendarDetails(){ @Test - public void getExperimentWithCalendarDetails(){ + public void experimentWithCalendarConstants(){ Calendar cal = Calendar.getInstance(); - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + cal.set(2013, Calendar.DECEMBER, 15, 23, 39, 54); + assertThat(cal.get(Calendar.DAY_OF_WEEK), is(1)); assertThat(cal.get(Calendar.DAY_OF_WEEK), is(Calendar.SUNDAY)); - assertThat(cal.get(Calendar.WEEK_OF_MONTH), is(2)); - assertThat(cal.get(Calendar.WEEK_OF_YEAR), is(50)); assertThat(cal.get(Calendar.DAY_OF_YEAR), is(349)); - } - - - @Test - public void addDaysToCalendar(){ - Calendar cal = Calendar.getInstance(); - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); - - cal.add(Calendar.HOUR_OF_DAY, -1); - assertThat(cal.get(Calendar.HOUR_OF_DAY), is(22)); - - cal.add(Calendar.MINUTE, 10); - assertThat(cal.get(Calendar.MINUTE), is(49)); - } - @Test - public void rollCalendar(){ - Calendar cal = Calendar.getInstance(); - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); - - cal.roll(Calendar.DAY_OF_MONTH,17); - - assertThat(cal.get(Calendar.YEAR), is(2013)); - assertThat(cal.get(Calendar.MONTH), is(Calendar.DECEMBER)); - assertThat(cal.get(Calendar.DAY_OF_MONTH), is(1)); - - cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + // week of month depends on first day of week + // some places use SUNDAY as first day + // set to MONDAY for our calculation + // and control Minimal Days in First Week + cal.setFirstDayOfWeek(Calendar.MONDAY); + cal.setMinimalDaysInFirstWeek(6); + assertThat(cal.get(Calendar.WEEK_OF_MONTH), is(2)); - cal.add(Calendar.DAY_OF_MONTH,17); - assertThat(cal.get(Calendar.YEAR), is(2014)); - assertThat(cal.get(Calendar.MONTH), is(Calendar.JANUARY)); - assertThat(cal.get(Calendar.DAY_OF_MONTH), is(1)); + // Week of the year, similarly requires the + // config to control first day + assertThat(cal.get(Calendar.WEEK_OF_YEAR), is(50)); } @Test @@ -164,4 +121,22 @@ public void incrementAndDecrementOtherFields(){ assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3)); } + @Test + public void rollCalendar(){ + Calendar cal = Calendar.getInstance(); + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + + cal.roll(Calendar.DAY_OF_MONTH,17); + + assertThat(cal.get(Calendar.YEAR), is(2013)); + assertThat(cal.get(Calendar.MONTH), is(Calendar.DECEMBER)); + assertThat(cal.get(Calendar.DAY_OF_MONTH), is(1)); + + cal.set(2013, Calendar.DECEMBER, 15, 23,39, 54); + + cal.add(Calendar.DAY_OF_MONTH,17); + assertThat(cal.get(Calendar.YEAR), is(2014)); + assertThat(cal.get(Calendar.MONTH), is(Calendar.JANUARY)); + assertThat(cal.get(Calendar.DAY_OF_MONTH), is(1)); + } } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap018properties/examples/PropertiesTest.java b/source/src/test/java/com/javafortesters/chap018properties/examples/PropertiesTest.java new file mode 100644 index 0000000..85b5f7c --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap018properties/examples/PropertiesTest.java @@ -0,0 +1,117 @@ +package com.javafortesters.chap018properties.examples; + +import org.junit.Test; + +import java.io.*; +import java.util.Properties; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +public class PropertiesTest { + + @Test + public void canCreateGetAndSetProperties(){ + + Properties properties = new Properties(); + + assertThat(properties.size(), is(0)); + + properties.setProperty("browser", "firefox"); + properties.setProperty("port", "80"); + assertThat( properties.getProperty("browser"), + is("firefox")); + assertThat( properties.getProperty("port"), + is("80")); + + assertThat( properties.getProperty("missing"), + is(nullValue())); + + assertThat( properties.getProperty("missing", "default"), + is("default")); + + assertThat( properties.containsKey("browser"), is(true)); + } + + + @Test + public void canDisplayTheProperties(){ + + Properties properties = new Properties(); + properties.setProperty("browser", "firefox"); + properties.setProperty("port", "80"); + + assertThat(properties.stringPropertyNames().size(), is (2)); + + for( String key : properties.stringPropertyNames()){ + System.out.println("Key: " + key + " " + + "Value: " + properties.getProperty(key)); + } + + properties.list(System.out); + } + + + @Test + public void canAccessSystemProperties(){ + + String workingDirectory = System.getProperty("user.dir"); + + String resourceFilePath = workingDirectory + + "/src/test/resources/" + + "property_files/" + + "static_example.properties"; + + Properties sys = System.getProperties(); + sys.list(System.out); + } + + @Test + public void exampleSetWebdriverChromeIfNotSet(){ + if(!System.getProperties().containsKey("webdriver.chrome.driver")){ + String currentDir = System.getProperty("user.dir"); + String chromeDriverLocation + = currentDir + + "/../tools/chromedriver/chromedriver.exe"; + System.setProperty("webdriver.chrome.driver", chromeDriverLocation); + } + } + + + @Test + public void simpleSaveLoadPropertiesFile() throws IOException { + + String tempDirectory = System.getProperty("java.io.tmpdir"); + String tempResourceFilePath = + new File(tempDirectory, + "tempFileForPropertiesStoreTest.properties") + .getAbsolutePath(); + + Properties saved = new Properties(); + saved.setProperty("prop1", "Hello"); + saved.setProperty("prop2", "World"); + + FileOutputStream outputFile = + new FileOutputStream(tempResourceFilePath); + saved.store(outputFile, "Hello There World"); + outputFile.close(); + + FileReader propertyFileReader = + new FileReader(tempResourceFilePath); + Properties loaded = new Properties(); + + try{ + loaded.load(propertyFileReader); + }finally{ + propertyFileReader.close(); + } + + assertThat(loaded.getProperty("prop1"), is("Hello")); + assertThat(loaded.getProperty("prop2"), is("World")); + + + new File(tempResourceFilePath).delete(); + + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap018properties/exercises/PropertyExercisesTest.java b/source/src/test/java/com/javafortesters/chap018properties/exercises/PropertyExercisesTest.java new file mode 100644 index 0000000..57eb000 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap018properties/exercises/PropertyExercisesTest.java @@ -0,0 +1,92 @@ +package com.javafortesters.chap018properties.exercises; + + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.Properties; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class PropertyExercisesTest { + + @Test + public void canCreateAndListTheProperties(){ + + Properties properties = new Properties(); + properties.setProperty("name", "bob"); + properties.setProperty("gender", "male"); + properties.setProperty("password", "paSSw0rd"); + + assertThat(properties.stringPropertyNames().size(), is (3)); + + for( String key : properties.stringPropertyNames()){ + System.out.println("Key: " + key + " " + + "Value: " + properties.getProperty(key)); + } + + properties.list(System.out); + + Assert.assertTrue(properties.containsKey("gender")); + Assert.assertEquals("bob", properties.getProperty("name")); + Assert.assertEquals("Admin", + properties.getProperty("permission", "Admin")); + } + + @Test + public void canAccessSystemProperties(){ + System.out.println("More Details:"); + System.out.println("docs.oracle.com/javase/tutorial/" + + "essential/environment/sysprop.html"); + + Properties sys = System.getProperties(); + sys.list(System.out); + } + + @Test + public void canSaveAndLoadAPropertiesFile() throws IOException { + + String tempDirectory = System.getProperty("java.io.tmpdir"); + String tempResourceFilePath = new File(tempDirectory, + System.currentTimeMillis() + + System.nanoTime() + + ".properties").getAbsolutePath(); + + Properties saved = new Properties(); + + long nanoTime = System.nanoTime(); + long millis = System.currentTimeMillis(); + + saved.setProperty("nanoTime", String.valueOf(nanoTime)); + saved.setProperty("millis", String.valueOf(millis)); + + FileOutputStream outputFile = + new FileOutputStream(tempResourceFilePath); + + saved.store(outputFile, "Time Data When File Written"); + outputFile.close(); + + FileReader propertyFileReader = + new FileReader(tempResourceFilePath); + Properties loaded = new Properties(); + + try{ + loaded.load(propertyFileReader); + }finally{ + propertyFileReader.close(); + } + + assertThat(loaded.getProperty("nanoTime"), + is(String.valueOf(nanoTime))); + assertThat(loaded.getProperty("millis"), + is(String.valueOf(millis))); + + new File(tempResourceFilePath).delete(); + + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap019files/examples/FileTest.java b/source/src/test/java/com/javafortesters/chap019files/examples/FileTest.java new file mode 100644 index 0000000..33623a0 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap019files/examples/FileTest.java @@ -0,0 +1,300 @@ +package com.javafortesters.chap019files.examples; + + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class FileTest { + + + // when running cross platform there are differences to be aware of + // the system properties may not have a / at the end + // and building file paths by hand can be problematic requiring + // lots of care + // so we use the Paths.get instead + // http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html + // Then use the returned Path object toFile to create the file object + // Both Path and Paths have been available since Java 1.7 + // https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html + + + @Test + public void aNewFileDoesNotCreateAFile() throws IOException { + File aTempFile = new File("d:/tempJavaForTesters.txt"); + assertThat(aTempFile.exists(), is(false)); + } + + @Test + public void pathsGetExampleForCrossPlatform() throws IOException { + + String tempDir = System.getProperty("java.io.tmpdir"); + + // you would probably just use File for this one + File theFile = Paths.get(tempDir, "file.txt").toFile(); + assertThat(theFile.getAbsolutePath(), + endsWith(File.separator + "file.txt")); + + theFile = Paths.get(tempDir, "temp1", "file.txt").toFile(); + assertThat(theFile.getAbsolutePath(), + endsWith(String.format("%s%s%1$s%s", + File.separator, "temp1", "file.txt"))); + + theFile = Paths.get(tempDir, "temp1","temp2", "temp3", "file.txt").toFile(); + assertThat(theFile.getAbsolutePath(), + endsWith(String.format("%s%s%1$s%s%1$s%s%1$s%s", + File.separator, "temp1", "temp2", "temp3", "file.txt"))); + } + + +/* + @Test + public void createAFileAndDeleteIt() throws IOException { + File aTempFile = new File("d:/tempJavaForTesters.txt"); + assertThat(aTempFile.exists(), is(false)); + + aTempFile.createNewFile(); + assertThat(aTempFile.exists(), is(true)); + + aTempFile.delete(); + assertThat(aTempFile.exists(), is(false)); + } +*/ + + // since the above example is commented out + // this checks that the basic code works + // in a platform independent way using Paths + @Test + public void createAFileAndDeleteItCodeCheck() throws IOException { + + /* for documentation of simple path + File aTempFile = Paths.get("d:", "tempJavaForTesters.txt").toFile(); + */ + + String tempDir = System.getProperty("java.io.tmpdir"); + File aTempFile = Paths.get(tempDir, "tempJavaForTesters.txt").toFile(); + + assertThat(aTempFile.exists(), is(false)); + + aTempFile.createNewFile(); + assertThat(aTempFile.exists(), is(true)); + + aTempFile.delete(); + assertThat(aTempFile.exists(), is(false)); + } + + + @Test + public void createAFileAndDeleteItAlternativeConstructor() throws IOException { + + String tempDir = System.getProperty("java.io.tmpdir"); + File aTempFile = new File(tempDir, "tempJavaForTesters.txt"); + assertThat(aTempFile.exists(), is(false)); + + aTempFile.createNewFile(); + assertThat(aTempFile.exists(), is(true)); + + aTempFile.delete(); + assertThat(aTempFile.exists(), is(false)); + } + + @Test + public void createLongerPathExample(){ + + String tempDirectory = System.getProperty("java.io.tmpdir"); + File aFile = new File(tempDirectory); + aFile = new File(aFile, "1"); + aFile = new File(aFile, "2"); + aFile = new File(aFile, "3"); + aFile = new File(aFile, "4"); + + // make it an easy cross platform comparison + String filePathWithDots = aFile.getAbsolutePath().replace(File.separator, "."); + assertTrue(filePathWithDots.endsWith(".1.2.3.4")); + + Path aPath = Paths.get(tempDirectory, "1", "2", "3", "4"); + assertEquals(aFile.getAbsolutePath(), + aPath.toFile().getAbsolutePath()); + } + + + + @Test + public void canonicalVsAbsolute() throws IOException { + + String tempDirectory = System.getProperty("java.io.tmpdir"); + + // create a directory path + // temp\\1\2\3\4\5 + // temp\\1 + // temp\\1\2\3\4\..\..\.. + // temp\\1\2\..\..\..\1 + + String currentMillis = String.valueOf(System.currentTimeMillis()); + + File bFile = new File(tempDirectory); + System.out.println(bFile.getName()); + + File aFile = new File(tempDirectory, currentMillis); + File oneDirectory = new File(aFile, "1"); + aFile = new File(oneDirectory, "2"); + aFile = new File(aFile, "3"); + aFile = new File(aFile, "4"); + aFile = new File(aFile, "5"); + + aFile.mkdirs(); + + System.out.println(oneDirectory.getAbsolutePath()); + System.out.println(oneDirectory.getCanonicalPath()); + System.out.println(aFile.getAbsolutePath()); + + assertTrue(oneDirectory.getCanonicalPath().endsWith(oneDirectory.getAbsolutePath())); + + File relative = new File(tempDirectory, currentMillis); + relative = new File(relative, "1"); + relative = new File(relative, "2"); + relative = new File(relative, "3"); + relative = new File(relative, "4"); + relative = new File(relative, ".."); //3 + relative = new File(relative, ".."); //2 + relative = new File(relative, ".."); //1 + + System.out.println(relative.getAbsolutePath()); + + assertTrue(relative.getCanonicalPath().endsWith(oneDirectory.getAbsolutePath())); + + relative = new File(tempDirectory, currentMillis); + relative = new File(relative, "1"); + relative = new File(relative, "2"); + relative = new File(relative, ".."); //1 + relative = new File(relative, ".."); //millis + relative = new File(relative, "1"); //1 + + System.out.println(relative.getAbsolutePath()); + + assertTrue(relative.getCanonicalPath().endsWith(oneDirectory.getAbsolutePath())); + } + + + @Test + public void mkdirsCreatesIntermediateDirs(){ + + String tempDirectory = System.getProperty("java.io.tmpdir"); + + File aDirectory = Paths.get(tempDirectory, + Long.toString(System.currentTimeMillis()), + Long.toString(System.currentTimeMillis())) + .toFile(); + + System.out.println(aDirectory.getAbsolutePath()); + + assertThat(aDirectory.mkdir(), is(false)); + assertThat(aDirectory.mkdirs(), is(true)); + } + + + @Test + public void mkdirsCreatesDirectories(){ + + String tempDirectory = System.getProperty("java.io.tmpdir"); + + File aFilePath = Paths.get(tempDirectory, + Long.toString(System.currentTimeMillis()), + "test.tmp") + .toFile(); + + System.out.println(aFilePath.getAbsolutePath()); + + // mkdir won't create this because it is temp/millis/test.tmp + + assertThat(aFilePath.mkdir(), is(false)); + assertThat(aFilePath.exists(), is(false)); + + // mkdir will create because it is just the temp/millis + File aDirectoryPath = Paths.get(tempDirectory, + Long.toString(System.currentTimeMillis())) + .toFile(); + + assertThat(aDirectoryPath.mkdir(), is(true)); + + } + + @Test + public void fileAndPathSeparator(){ + assertTrue("Unrecognised OS file separator", + File.separator.equals("\\") || + File.separator.equals("/")); + assertTrue("Unrecognised OS path separator", + File.pathSeparator.equals(";") || + File.pathSeparator.equals(":")); + } + + @Test + public void createATempFileAndDeleteOnExit(){ + + try { + File aTempFile = File.createTempFile("prefix", "suffix"); + aTempFile.deleteOnExit(); + + System.out.println(aTempFile.getAbsolutePath()); + + String tempDirectory = System.getProperty("java.io.tmpdir"); + + assertThat( aTempFile.getName().startsWith("prefix"), is(true)); + assertThat( aTempFile.getName().endsWith("suffix"), is(true)); + + assertTrue(System.getProperty("java.io.tmpdir"). + startsWith(aTempFile.getParent())); + + assertThat(aTempFile.getAbsolutePath().endsWith("suffix"), + is(true)); + assertThat(aTempFile.getAbsolutePath().startsWith( + System.getProperty("java.io.tmpdir")), is(true)); + + assertThat(aTempFile.getCanonicalPath().endsWith("suffix"), + is(true)); + assertThat(aTempFile.getCanonicalPath().contains( + System.getProperty("java.io.tmpdir")), is(true)); + + assertThat(aTempFile.exists(), is(true)); + + // the prefix needs to be 3 chars or longer otherwise java.lang.IllegalArgumentException is thrown + String userDirectory = System.getProperty("user.dir"); + + aTempFile = File.createTempFile("pre", null, + new File(System.getProperty("user.dir"))); + + System.out.println(aTempFile.getAbsolutePath()); + aTempFile.deleteOnExit(); + + assertThat(aTempFile.getAbsolutePath().endsWith(".tmp"), is(true)); + assertThat(aTempFile.getAbsolutePath().startsWith(userDirectory), is(true)); + + } catch (IOException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + + + } + + @Test + public void listTempDirectory(){ + File tempDir = new File(System.getProperty("java.io.tmpdir")); + + String[] fileList = tempDir.list(); + + for(String fileInList : fileList){ + System.out.println(fileInList); + } + } + +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/files/ReadTextFilesTest.java b/source/src/test/java/com/javafortesters/chap019files/examples/ReadTextFilesTest.java similarity index 95% rename from source/src/test/java/com/javafortesters/files/ReadTextFilesTest.java rename to source/src/test/java/com/javafortesters/chap019files/examples/ReadTextFilesTest.java index 80ccdeb..cb30101 100644 --- a/source/src/test/java/com/javafortesters/files/ReadTextFilesTest.java +++ b/source/src/test/java/com/javafortesters/chap019files/examples/ReadTextFilesTest.java @@ -1,10 +1,8 @@ -package com.javafortesters.files; +package com.javafortesters.chap019files.examples; import org.junit.Test; import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/source/src/test/java/com/javafortesters/files/WriteTextFilesTest.java b/source/src/test/java/com/javafortesters/chap019files/examples/WriteTextFilesTest.java similarity index 98% rename from source/src/test/java/com/javafortesters/files/WriteTextFilesTest.java rename to source/src/test/java/com/javafortesters/chap019files/examples/WriteTextFilesTest.java index a8bb339..ea27db5 100644 --- a/source/src/test/java/com/javafortesters/files/WriteTextFilesTest.java +++ b/source/src/test/java/com/javafortesters/chap019files/examples/WriteTextFilesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.files; +package com.javafortesters.chap019files.examples; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/files/FileExercisesTest.java b/source/src/test/java/com/javafortesters/chap019files/exercises/FileExercisesTest.java similarity index 59% rename from source/src/test/java/com/javafortesters/files/FileExercisesTest.java rename to source/src/test/java/com/javafortesters/chap019files/exercises/FileExercisesTest.java index a493891..f333f5b 100644 --- a/source/src/test/java/com/javafortesters/files/FileExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap019files/exercises/FileExercisesTest.java @@ -1,5 +1,6 @@ -package com.javafortesters.files; +package com.javafortesters.chap019files.exercises; +import org.junit.Assert; import org.junit.Test; import java.io.*; @@ -13,21 +14,30 @@ public class FileExercisesTest { @Test public void createTempFileVaryTheParameters() throws IOException { - // on windows these files are in %TEMP% + // on Windows these files are in %TEMP% + // on Mac these files are in $TMPDIR File temp1 = File.createTempFile("temp1", null); File temp2 = File.createTempFile("temp2OutFile", ".out"); + + assertThat(temp1.exists(), is(true)); + assertThat(temp2.exists(), is(true)); + + temp1.deleteOnExit(); + temp2.deleteOnExit(); } @Test - public void fileListRoots(){ + public void writeOutTheFileListRoots(){ File[] roots = File.listRoots(); + Assert.assertTrue(roots.length > 0); for(File aFile : roots){ System.out.println(aFile.getAbsolutePath()); } } + @Test public void createATempFileWithCustomCode() throws IOException { @@ -35,19 +45,17 @@ public void createATempFileWithCustomCode() throws IOException { String fileName = "prefix" + System.currentTimeMillis() + ".tmp"; File aTempFile = new File(directory, fileName); - assertThat(aTempFile.exists(), is(false)); aTempFile.createNewFile(); - assertThat(aTempFile.exists(), is(true)); aTempFile.delete(); - assertThat(aTempFile.exists(), is(false)); } + @Test public void writeATestToCheckCanonicalConversion() throws IOException { @@ -55,15 +63,45 @@ public void writeATestToCheckCanonicalConversion() throws IOException { File absolute2 = new File("C:/1/2/../../1"); File canonical = new File("C:/1"); - assertThat(canonical.getAbsolutePath(), is(canonical.getCanonicalPath())); - - assertThat(canonical.getAbsolutePath(), is(absolute1.getCanonicalPath())); - assertThat(canonical.getAbsolutePath(), is(absolute2.getCanonicalPath())); + assertThat(trimOsStuff( + canonical.getAbsolutePath()), + is(trimOsStuff( + canonical.getCanonicalPath()))); + assertThat(trimOsStuff( + canonical.getAbsolutePath()), + is(trimOsStuff( + absolute1.getCanonicalPath()))); + assertThat(trimOsStuff( + canonical.getAbsolutePath()), + is(trimOsStuff( + absolute2.getCanonicalPath()))); assertThat(absolute1.getAbsolutePath().contains(".."), is(true)); assertThat(absolute2.getAbsolutePath().contains(".."), is(true)); } + // The above code runs fine on a Mac and Windows without needing + // trimOsStuff + // but on Linux, it seems to add a ./ in the middle of the absolute path + // e.g. /home/travis/build/eviltester/javaForTestersCode/./source/C:/1 + // So I add the following method to trim out the operating system addition to + // the path e.g. anything before the C: + private String trimOsStuff(String absolutePath) { + int posOfDrive = absolutePath.indexOf("C:"); + String pathWithoutOsPrefixes = absolutePath.substring(posOfDrive); + System.out.println(String.format( + "trimOsStuff: %s became %s",absolutePath, pathWithoutOsPrefixes)); + return pathWithoutOsPrefixes; + } + + + @Test + public void checkThatTheTempDirectoryIsADirectory(){ + File tempDir = new File(System.getProperty("java.io.tmpdir")); + + assertThat(tempDir.isDirectory(), is(true)); + assertThat(tempDir.isFile(), is(false)); + } @Test public void exerciseWriteToAPrintWriterThenAppend() throws IOException { @@ -92,18 +130,46 @@ public void exerciseWriteToAPrintWriterThenAppend() throws IOException { } @Test - public void checkThatTheTempDirectoryIsADirectory(){ - File tempDir = new File(System.getProperty("java.io.tmpdir")); + public void spaceMethods() throws IOException { - assertThat(tempDir.isDirectory(), is(true)); - assertThat(tempDir.isFile(), is(false)); + File temp = new File(System.getProperty("java.io.tmpdir")); + + long freeSpace = temp.getFreeSpace(); + long totalSpace = temp.getTotalSpace(); + long usableSpace = temp.getUsableSpace(); + + File outputFile = writeTheTestDataFile(5); + assertThat(outputFile.length(), is(expectedFileSize(5))); + + System.out.println("Length " + outputFile.length() ); + System.out.println("Free " + freeSpace ); + System.out.println("Total " + totalSpace ); + System.out.println("Usable " + usableSpace); + } + + private long expectedFileSize(int lines){ + String lineEnd = System.lineSeparator(); + return (("line x".length() + lineEnd.length())*lines); } + private File writeTheTestDataFile(int lines) throws IOException { + File outputFile = File.createTempFile( + "forReading" + lines + "_", null); + PrintWriter print = new PrintWriter( + new BufferedWriter( + new FileWriter(outputFile))); + for(int line=0; line " + lastModified; - System.out.println(outputString); } } diff --git a/source/src/test/java/com/javafortesters/files/FilesTest.java b/source/src/test/java/com/javafortesters/chap019files/exercises/FilesCopyMoveTest.java similarity index 85% rename from source/src/test/java/com/javafortesters/files/FilesTest.java rename to source/src/test/java/com/javafortesters/chap019files/exercises/FilesCopyMoveTest.java index f8cbb23..1a57a48 100644 --- a/source/src/test/java/com/javafortesters/files/FilesTest.java +++ b/source/src/test/java/com/javafortesters/chap019files/exercises/FilesCopyMoveTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.files; +package com.javafortesters.chap019files.exercises; import org.junit.Test; @@ -13,11 +13,10 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class FilesTest { +public class FilesCopyMoveTest { @Test public void copyFile() throws IOException { - File copyThis = writeTheTestDataFile(); File toThis = new File(copyThis.getCanonicalPath() + ".copy"); @@ -31,7 +30,6 @@ public void copyFile() throws IOException { @Test public void moveFile() throws IOException { - File moveThis = writeTheTestDataFile(); File toThis = new File(moveThis.getCanonicalPath() + ".moved"); @@ -45,18 +43,15 @@ public void moveFile() throws IOException { assertThat(moveThis.exists(), is(false)); } - - private File writeTheTestDataFile() throws IOException { File outputFile = File.createTempFile("forReading", null); - PrintWriter print = new PrintWriter(new BufferedWriter( new FileWriter(outputFile))); - + PrintWriter print = new PrintWriter( + new BufferedWriter( + new FileWriter(outputFile))); for(int lineNumber = 1; lineNumber < 6; lineNumber++){ print.println("line " + lineNumber); } - print.close(); return outputFile; } - } \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/math/MathTest.java b/source/src/test/java/com/javafortesters/chap020mathbigdecimal/examples/MathAndBigDecimalTest.java similarity index 95% rename from source/src/test/java/com/javafortesters/math/MathTest.java rename to source/src/test/java/com/javafortesters/chap020mathbigdecimal/examples/MathAndBigDecimalTest.java index cfdc48c..9027817 100644 --- a/source/src/test/java/com/javafortesters/math/MathTest.java +++ b/source/src/test/java/com/javafortesters/chap020mathbigdecimal/examples/MathAndBigDecimalTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.math; +package com.javafortesters.chap020mathbigdecimal.examples; import org.junit.Test; @@ -8,7 +8,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class MathTest { +public class MathAndBigDecimalTest { @Test(expected = java.lang.AssertionError.class) public void whyBigDecimal(){ diff --git a/source/src/test/java/com/javafortesters/math/MathExercisesTest.java b/source/src/test/java/com/javafortesters/chap020mathbigdecimal/exercises/MathAndBigDecimalExercisesTest.java similarity index 84% rename from source/src/test/java/com/javafortesters/math/MathExercisesTest.java rename to source/src/test/java/com/javafortesters/chap020mathbigdecimal/exercises/MathAndBigDecimalExercisesTest.java index a53a77f..5287012 100644 --- a/source/src/test/java/com/javafortesters/math/MathExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap020mathbigdecimal/exercises/MathAndBigDecimalExercisesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.math; +package com.javafortesters.chap020mathbigdecimal.exercises; import org.junit.Test; @@ -10,7 +10,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -public class MathExercisesTest { +public class MathAndBigDecimalExercisesTest { @Test public void convinceYourselfOfBigDecimalUsage(){ @@ -27,9 +27,9 @@ public void convinceYourselfOfBigDecimalUsage(){ assertThat(inPennies, is(250)); BigDecimal bdTotal = new BigDecimal("5"). - subtract(new BigDecimal("0.30")). - subtract(new BigDecimal(("0.47"))). - subtract(new BigDecimal("1.73")); + subtract(new BigDecimal("0.30")). + subtract(new BigDecimal(("0.47"))). + subtract(new BigDecimal("1.73")); assertThat(bdTotal, is(new BigDecimal("2.50"))); } diff --git a/source/src/test/java/com/javafortesters/collections/SortedMapTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedMapTest.java similarity index 97% rename from source/src/test/java/com/javafortesters/collections/SortedMapTest.java rename to source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedMapTest.java index 7b16cc4..614211e 100644 --- a/source/src/test/java/com/javafortesters/collections/SortedMapTest.java +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedMapTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap021collectionsrevisited.examples; import com.javafortesters.domainentities.User; @@ -6,9 +6,7 @@ import org.junit.Test; import java.util.SortedMap; -import java.util.SortedSet; import java.util.TreeMap; -import java.util.TreeSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/source/src/test/java/com/javafortesters/collections/SortedSetTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedSetTest.java similarity index 98% rename from source/src/test/java/com/javafortesters/collections/SortedSetTest.java rename to source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedSetTest.java index 8583fef..955dcb1 100644 --- a/source/src/test/java/com/javafortesters/collections/SortedSetTest.java +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/examples/SortedSetTest.java @@ -1,11 +1,9 @@ -package com.javafortesters.collections; +package com.javafortesters.chap021collectionsrevisited.examples; import com.javafortesters.domainentities.User; import com.javafortesters.domainentities.UserComparator; import org.junit.Test; -import java.util.Collection; -import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; diff --git a/source/src/test/java/com/javafortesters/collections/MapExercisesTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetAndMapExercisesTest.java similarity index 86% rename from source/src/test/java/com/javafortesters/collections/MapExercisesTest.java rename to source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetAndMapExercisesTest.java index 3f2e912..6f8f0c9 100644 --- a/source/src/test/java/com/javafortesters/collections/MapExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetAndMapExercisesTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap021collectionsrevisited.exercises; import org.junit.Test; @@ -9,7 +9,7 @@ import static org.junit.Assert.assertEquals; -public class MapExercisesTest { +public class SortedSetAndMapExercisesTest { @Test public void exerciseCanGetAllKeysAsSortedSet(){ diff --git a/source/src/test/java/com/javafortesters/collections/SortedSetExercisesUserClassTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesComparableUserClassTest.java similarity index 86% rename from source/src/test/java/com/javafortesters/collections/SortedSetExercisesUserClassTest.java rename to source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesComparableUserClassTest.java index b391847..bb2dd0d 100644 --- a/source/src/test/java/com/javafortesters/collections/SortedSetExercisesUserClassTest.java +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesComparableUserClassTest.java @@ -1,4 +1,4 @@ -package com.javafortesters.collections; +package com.javafortesters.chap021collectionsrevisited.exercises; import com.javafortesters.domainentities.interim.comparator.User; import org.junit.Test; @@ -8,10 +8,10 @@ import static org.junit.Assert.assertEquals; -public class SortedSetExercisesUserClassTest { +public class SortedSetExercisesComparableUserClassTest { @Test - public void sortedSetWithComparatorForUser(){ + public void sortedSetWithComparableUser(){ User bob = new User("Bob", "pA55Word"); // 11 User dupebob = new User("Bob", "hello"); User rich = new User("Richie", "RichieRichieRich"); // 22 diff --git a/source/src/test/java/com/javafortesters/collections/SortedSetExercisesTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesTest.java similarity index 92% rename from source/src/test/java/com/javafortesters/collections/SortedSetExercisesTest.java rename to source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesTest.java index 37ffc43..7dba5bd 100644 --- a/source/src/test/java/com/javafortesters/collections/SortedSetExercisesTest.java +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesTest.java @@ -1,7 +1,6 @@ -package com.javafortesters.collections; +package com.javafortesters.chap021collectionsrevisited.exercises; import com.javafortesters.domainentities.User; -import com.javafortesters.domainentities.UserComparator; import com.javafortesters.domainentities.UserComparatorDisallowDupes; import org.junit.Test; diff --git a/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassNoValEqualZeroComparatorTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassNoValEqualZeroComparatorTest.java new file mode 100644 index 0000000..c6137e6 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassNoValEqualZeroComparatorTest.java @@ -0,0 +1,60 @@ +package com.javafortesters.chap021collectionsrevisited.exercises; + +import com.javafortesters.domainentities.interim.comparator.User; +import org.junit.Test; + +import java.util.Comparator; +import java.util.SortedSet; +import java.util.TreeSet; + +import static org.junit.Assert.assertEquals; + +public class SortedSetExercisesUserClassNoValEqualZeroComparatorTest { + + @Test + public void sortedSetWithComparatorForUserWithNoValEqualZero(){ + User bob = new User("Bob", "pA55Word"); // 11 + User dupebob = new User("Bob", "hello"); + User rich = new User("Richie", "RichieRichieRich"); // 22 + User dupebob2 = new User("Bob", "BobsMightyBigBobPassword"); + User mrBeer = new User("Stafford", "sys"); // 11 + + SortedSet userSortedList = + new TreeSet( + new UserComparatorDisallowDupesNoValEqualZero()); + + userSortedList.add(bob); + userSortedList.add(dupebob); + userSortedList.add(rich); + userSortedList.add(dupebob2); + assertEquals(2, userSortedList.size()); + userSortedList.add(mrBeer); + assertEquals("Mr Beer could not be added", 2, userSortedList.size()); + } + + private class UserComparatorDisallowDupesNoValEqualZero implements Comparator { + + public int compare(Object oUser1, Object oUser2) { + User user1 = (User)oUser1; + User user2 = (User)oUser2; + + if(user1.getUsername().compareTo(user2.getUsername())==0){ + return 0; + } + + int user1Comparator = user1.getPassword().length() + + user1.getUsername().length(); + + int user2Comparator = user2.getPassword().length() + + user2.getUsername().length(); + + int val = user1Comparator - user2Comparator; + + // if(val==0){ + // val = user1.getUsername().compareTo(user2.getUsername()); + // } + + return val; + } + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassSeeComparatorInActionTest.java b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassSeeComparatorInActionTest.java new file mode 100644 index 0000000..a6cce75 --- /dev/null +++ b/source/src/test/java/com/javafortesters/chap021collectionsrevisited/exercises/SortedSetExercisesUserClassSeeComparatorInActionTest.java @@ -0,0 +1,70 @@ +package com.javafortesters.chap021collectionsrevisited.exercises; + +import com.javafortesters.domainentities.interim.comparator.User; +import org.junit.Test; + +import java.util.Comparator; +import java.util.SortedSet; +import java.util.TreeSet; + +import static org.junit.Assert.assertEquals; + +public class SortedSetExercisesUserClassSeeComparatorInActionTest { + + @Test + public void sortedSetWithComparatorForUserWithNoValEqualZero(){ + User bob = new User("Bob", "pA55Word"); // 11 + User dupebob = new User("Bob", "hello"); + User rich = new User("Richie", "RichieRichieRich"); // 22 + User dupebob2 = new User("Bob", "BobsMightyBigBobPassword"); + User mrBeer = new User("Stafford", "sys"); // 11 + + SortedSet userSortedList = + new TreeSet( + new UserComparatorDisallowDupes()); + + userSortedList.add(bob); + userSortedList.add(dupebob); + userSortedList.add(rich); + userSortedList.add(dupebob2); + userSortedList.add(mrBeer); + + assertEquals(3, userSortedList.size()); + + User[] users = new User[userSortedList.size()]; + userSortedList.toArray(users); + + assertEquals(bob.getUsername(), users[0].getUsername()); + assertEquals(mrBeer.getUsername(), users[1].getUsername()); + assertEquals(rich.getUsername(), users[2].getUsername()); + } + + private class UserComparatorDisallowDupes implements Comparator { + + public int compare(Object oUser1, Object oUser2) { + User user1 = (User)oUser1; + User user2 = (User)oUser2; + + if(user1.getUsername().compareTo(user2.getUsername())==0){ + return 0; + } + + int user1Comparator = user1.getPassword().length() + + user1.getUsername().length(); + + int user2Comparator = user2.getPassword().length() + + user2.getUsername().length(); + + int val = user1Comparator - user2Comparator; + + + if(val==0){ + val = user1.getUsername().compareTo(user2.getUsername()); + } + + System.out.println("Compare " + user1.getUsername() + + " with " + user2.getUsername() + " = " + val); + return val; + } + } +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/datestimes/TimeTest.java b/source/src/test/java/com/javafortesters/datestimes/TimeTest.java deleted file mode 100644 index 7300049..0000000 --- a/source/src/test/java/com/javafortesters/datestimes/TimeTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.javafortesters.datestimes; - -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class TimeTest { - - @Test - public void currentTimeMillis(){ - long startTime = System.currentTimeMillis(); - - for(int x=0; x < 10; x++){ - System.out.println("Current Time " + - System.currentTimeMillis()); - } - - long endTime = System.currentTimeMillis(); - System.out.println("Total Time " + (endTime - startTime)); - } - - - @Test - public void createAUniqueUserID(){ - - String userID = "user" + System.currentTimeMillis(); - - System.out.println(userID); - } - - @Test - public void createAUniqueUserIDAllChars(){ - - String initialUserID = "user" + System.currentTimeMillis(); - System.out.println(initialUserID); - - String userID = initialUserID; - - for(int x = 0; x< 10; x++){ - userID = userID.replace( "" + x, "" + ((char)('A'+x))); - } - - assertThat(userID.contains("0"), is(false)); - assertThat(userID.contains("1"), is(false)); - assertThat(userID.contains("2"), is(false)); - assertThat(userID.contains("3"), is(false)); - assertThat(userID.contains("4"), is(false)); - assertThat(userID.contains("5"), is(false)); - assertThat(userID.contains("6"), is(false)); - assertThat(userID.contains("7"), is(false)); - assertThat(userID.contains("8"), is(false)); - assertThat(userID.contains("9"), is(false)); - - assertThat(initialUserID.length(), is(userID.length())); - - System.out.println(userID); - } - - @Test - public void nanoTime(){ - long startTime = System.nanoTime(); - - for(int x=0; x < 10; x++){ - System.out.println("Current Time " + System.nanoTime()); - } - - long endTime = System.nanoTime(); - System.out.println("Total Time " + (endTime - startTime)); - } -} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/domainentities/UserTest.java b/source/src/test/java/com/javafortesters/domainentities/UserTest.java new file mode 100644 index 0000000..a5857b5 --- /dev/null +++ b/source/src/test/java/com/javafortesters/domainentities/UserTest.java @@ -0,0 +1,54 @@ +package com.javafortesters.domainentities; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class UserTest { + + @Test + public void canConstructANewUser(){ + User user = new User(); + } + + @Test + public void userHasDefaultUsernameAndPassword(){ + + User user = new User(); + + assertEquals("default username expected", + "username", + user.getUsername()); + + assertEquals("default password expected", + "password", + user.getPassword()); + } + + @Test + public void canConstructWithUsernameAndPassword(){ + + User user = new User("admin", "pA55w0rD"); + + assertEquals("given username expected", + "admin", + user.getUsername()); + + assertEquals("given password expected", + "pA55w0rD", + user.getPassword()); + } + + @Test + public void canSetPasswordAfterConstructed(){ + + User user = new User(); + + user.setPassword("PaZZwor6"); + + assertEquals("setter password expected", + "PaZZwor6", + user.getPassword()); + } + +} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/files/AdditionalFileMethodsTest.java b/source/src/test/java/com/javafortesters/files/AdditionalFileMethodsTest.java deleted file mode 100644 index 8d83880..0000000 --- a/source/src/test/java/com/javafortesters/files/AdditionalFileMethodsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.javafortesters.files; - -import org.junit.Test; - -import java.io.*; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class AdditionalFileMethodsTest { - - - @Test - public void spaceMethods() throws IOException { - - File temp = new File(System.getProperty("java.io.tmpdir")); - - long freeSpace = temp.getFreeSpace(); - long totalSpace = temp.getTotalSpace(); - long usableSpace = temp.getUsableSpace(); - - File outputFile = writeTheTestDataFile(5); - assertThat(outputFile.length(), is(expectedFileSize(5))); - - System.out.println("Length " + outputFile.length() ); - System.out.println("Free " + freeSpace ); - System.out.println("Total " + totalSpace ); - System.out.println("Usable " + usableSpace); - } - - private long expectedFileSize(int lines){ - String lineEnd = System.lineSeparator(); - return (("line x".length() + lineEnd.length())*lines); - } - - private File writeTheTestDataFile(int lines) throws IOException { - File outputFile = File.createTempFile("forReading" + lines + "_", null); - PrintWriter print = new PrintWriter(new BufferedWriter( new FileWriter(outputFile))); - - for(int line=0; line\1\2\3\4\5 - // temp\\1 - // temp\\1\2\3\4\..\..\.. - // temp\\1\2\..\..\..\1 - - String currentMillis = String.valueOf(System.currentTimeMillis()); - - File bFile = new File(tempDirectory); - System.out.println(bFile.getName()); - - File aFile = new File(tempDirectory, currentMillis); - File oneDirectory = new File(aFile, "1"); - aFile = new File(oneDirectory, "2"); - aFile = new File(aFile, "3"); - aFile = new File(aFile, "4"); - aFile = new File(aFile, "5"); - - aFile.mkdirs(); - - System.out.println(oneDirectory.getAbsolutePath()); - System.out.println(aFile.getAbsolutePath()); - - assertThat(oneDirectory.getAbsolutePath(), is(oneDirectory.getCanonicalPath())); - - File relative = new File(tempDirectory, currentMillis); - relative = new File(relative, "1"); - relative = new File(relative, "2"); - relative = new File(relative, "3"); - relative = new File(relative, "4"); - relative = new File(relative, ".."); //3 - relative = new File(relative, ".."); //2 - relative = new File(relative, ".."); //1 - - System.out.println(relative.getAbsolutePath()); - - assertThat(oneDirectory.getAbsolutePath(), is(relative.getCanonicalPath())); - - relative = new File(tempDirectory, currentMillis); - relative = new File(relative, "1"); - relative = new File(relative, "2"); - relative = new File(relative, ".."); //1 - relative = new File(relative, ".."); //millis - relative = new File(relative, "1"); //1 - - System.out.println(relative.getAbsolutePath()); - - assertThat(oneDirectory.getAbsolutePath(), is(relative.getCanonicalPath())); - } - - - @Test - public void mkdirsCreatesIntermediateDirs(){ - - String tempDirectory = System.getProperty("java.io.tmpdir"); - String newDirectoryStructure = tempDirectory + - System.currentTimeMillis() + - File.separator + - System.currentTimeMillis(); - File aDirectory = new File(newDirectoryStructure); - - System.out.println(aDirectory.getAbsolutePath()); - - assertThat(aDirectory.mkdir(), is(false)); - assertThat(aDirectory.mkdirs(), is(true)); - } - - - @Test - public void mkdirsCreatesDirectories(){ - - String tempDirectory = System.getProperty("java.io.tmpdir"); - - String newDirectoryStructure = tempDirectory + - System.currentTimeMillis(); - //File.separator + - //System.currentTimeMillis(); - - System.out.println(newDirectoryStructure); - - // mkdir won't create this because it is temp/millis/test.tmp - File aDirectory = new File(newDirectoryStructure, "test.tmp"); - assertThat(aDirectory.mkdir(), is(false)); - assertThat(aDirectory.exists(), is(false)); - - // will create because it is just the temp/millis - aDirectory = new File(newDirectoryStructure); - assertThat(aDirectory.mkdir(), is(true)); - - } - - @Test - public void fileAndPathSeparator(){ - assertEquals("Are you running this on windows?", - "\\", File.separator); - assertEquals("Are you running this on windows?", - ";", File.pathSeparator); - } - - @Test - public void createATempFileAndDeleteOnExit(){ - - try { - File aTempFile = File.createTempFile("prefix", "suffix"); - aTempFile.deleteOnExit(); - - System.out.println(aTempFile.getAbsolutePath()); - - String tempDirectory = System.getProperty("java.io.tmpdir"); - - assertThat( aTempFile.getName().startsWith("prefix"), is(true)); - assertThat( aTempFile.getName().endsWith("suffix"), is(true)); - - assertThat( aTempFile.getParent() + File.separator, - is(System.getProperty("java.io.tmpdir"))); - - assertThat(aTempFile.getAbsolutePath().endsWith("suffix"), is(true)); - assertThat(aTempFile.getAbsolutePath().startsWith( - System.getProperty("java.io.tmpdir")), is(true)); - - assertThat(aTempFile.getCanonicalPath().endsWith("suffix"), is(true)); - assertThat(aTempFile.getCanonicalPath().startsWith( - System.getProperty("java.io.tmpdir")), is(true)); - - assertThat(aTempFile.exists(), is(true)); - - - - // the prefix needs to be 3 chars or longer otherwise java.lang.IllegalArgumentException is thrown - String userDirectory = System.getProperty("user.dir"); - - aTempFile = File.createTempFile("pre", null, - new File(System.getProperty("user.dir"))); - - System.out.println(aTempFile.getAbsolutePath()); - aTempFile.deleteOnExit(); - - assertThat(aTempFile.getAbsolutePath().endsWith(".tmp"), is(true)); - assertThat(aTempFile.getAbsolutePath().startsWith(userDirectory), is(true)); - - } catch (IOException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - - - } - - @Test - public void listTempDirectory(){ - File tempDir = new File(System.getProperty("java.io.tmpdir")); - - String[] fileList = tempDir.list(); - - for(String fileInList : fileList){ - System.out.println(fileInList); - } - } - -} \ No newline at end of file diff --git a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethod/MyFirstTest.java b/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethod/MyFirstTest.java deleted file mode 100644 index 6468484..0000000 --- a/source/src/test/java/com/javafortesters/myfirsttest/interim/emptyMethod/MyFirstTest.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.javafortesters.myfirsttest.interim.emptyMethod; - -public class MyFirstTest { - - public void canAddTwoPlusTwo(){ - } -} diff --git a/source/src/test/java/com/javafortesters/properties/PropertiesTest.java b/source/src/test/java/com/javafortesters/properties/PropertiesTest.java deleted file mode 100644 index e7c1499..0000000 --- a/source/src/test/java/com/javafortesters/properties/PropertiesTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.javafortesters.properties; - -import org.junit.Test; - -import java.io.*; -import java.util.Properties; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -public class PropertiesTest { - - @Test - public void canCreateGetAndSetProperties(){ - - Properties properties = new Properties(); - properties.setProperty("browser", "firefox"); - properties.setProperty("port", "80"); - assertThat( properties.getProperty("browser"), - is("firefox")); - assertThat( properties.getProperty("port"), - is("80")); - - assertThat( properties.getProperty("missing"), - is(nullValue())); - - assertThat( properties.getProperty("proxy", "localhost"), - is("localhost")); - - assertThat( properties.containsKey("browser"), is(true)); - } - - - @Test - public void canDisplayTheProperties(){ - - Properties properties = new Properties(); - properties.setProperty("browser", "firefox"); - properties.setProperty("port", "80"); - - assertThat(properties.stringPropertyNames().size(), is (2)); - - for( String key : properties.stringPropertyNames()){ - System.out.println("Key: " + key + " " + - "Value: " + properties.getProperty(key)); - } - - properties.list(System.out); - } - - - @Test - public void canAccessSystemProperties(){ - - String workingDirectory = System.getProperty("user.dir"); - - String resourceFilePath = workingDirectory + - "/src/test/resources/" + - "property_files/" + - "static_example.properties"; - - Properties sys = System.getProperties(); - sys.list(System.out); - } - - @Test - public void exampleSetWebdriverChromeIfNotSet(){ - if(!System.getProperties().containsKey("webdriver.chrome.driver")){ - String currentDir = System.getProperty("user.dir"); - String chromeDriverLocation = currentDir + - "/../tools/chromedriver/chromedriver.exe"; - System.setProperty("webdriver.chrome.driver", chromeDriverLocation); - } - } - - @Test - public void canReadAPropertiesFileReader() throws IOException { - - String workingDirectory = System.getProperty("user.dir"); - String resourceFilePath = workingDirectory + - "/src/test/resources/" + - "property_files/" + - "static_example.properties"; - - Properties sample = new Properties(); - FileReader propertyFileReader = new FileReader(resourceFilePath); - - try{ - sample.load(new FileReader(resourceFilePath)); - }finally{ - propertyFileReader.close(); - } - - assertThat(sample.getProperty("browser"), is("chrome")); - } - - @Test - public void canReadAPropertiesFileInputStream() throws IOException { - - String workingDirectory = System.getProperty("user.dir"); - String resourceFilePath = workingDirectory + - "/src/test/resources/" + - "property_files/" + - "static_example.properties"; - - Properties sample = new Properties(); - FileInputStream propertyFileInputStream = new - FileInputStream(resourceFilePath); - - try{ - sample.load(propertyFileInputStream); - }finally{ - propertyFileInputStream.close(); - } - - assertThat(sample.getProperty("browser"), is("chrome")); - } - - - @Test - public void simpleSavePropertiesFile() throws IOException { - - String tempDirectory = System.getProperty("java.io.tmpdir"); - String tempResourceFilePath = tempDirectory + - "tempFileForPropertiesStoreTest.properties"; - - Properties saved = new Properties(); - saved.setProperty("prop1", "Hello"); - saved.setProperty("prop2", "World"); - - FileOutputStream outputFile = new FileOutputStream(tempResourceFilePath); - saved.store(outputFile, "Hello There World"); - outputFile.close(); - - - FileReader propertyFileReader = new FileReader(tempResourceFilePath); - Properties loaded = new Properties(); - - try{ - loaded.load(propertyFileReader); - }finally{ - propertyFileReader.close(); - } - - assertThat(loaded.getProperty("prop1"), is("Hello")); - assertThat(loaded.getProperty("prop2"), is("World")); - - new File(tempResourceFilePath).delete(); - } - - @Test - public void canSaveAPropertiesFile() throws IOException { - - String tempDirectory = System.getProperty("java.io.tmpdir"); - String tempResourceFilePath = tempDirectory + - System.currentTimeMillis() + - System.nanoTime() + - ".properties"; - - Properties saved = new Properties(); - - - long nanoTime = System.nanoTime(); - long millis = System.currentTimeMillis(); - - saved.setProperty("nanoTime", String.valueOf(nanoTime)); - saved.setProperty("millis", String.valueOf(millis)); - - FileOutputStream outputFile = new FileOutputStream(tempResourceFilePath); - - saved.store(outputFile, "Time Data When File Written"); - outputFile.close(); - - - FileReader propertyFileReader = new FileReader(tempResourceFilePath); - Properties loaded = new Properties(); - - try{ - loaded.load(propertyFileReader); - }finally{ - propertyFileReader.close(); - } - - assertThat(loaded.getProperty("nanoTime"), is(String.valueOf(nanoTime))); - assertThat(loaded.getProperty("millis"), is(String.valueOf(millis))); - - new File(tempResourceFilePath).delete(); - - } -} \ No newline at end of file