From 84cdc0460e6c800b89ae2e74bb56e0a96a1e181f Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 1 Dec 2026 18:53:03 +0530 Subject: [PATCH 1/3] Generate all tests using generator --- .../acronym/src/test/java/AcronymTest.java | 8 +- .../src/test/java/AffineCipherTest.java | 153 ++- .../src/test/java/BaseConverterTest.java | 175 ++-- .../src/test/java/AllergiesTest.java | 484 ++++----- .../src/test/java/AlphameticsTest.java | 124 ++- .../anagram/src/test/java/AnagramTest.java | 171 ++-- .../src/test/java/ArmstrongNumbersTest.java | 44 +- .../src/test/java/AtbashTest.java | 100 +- .../src/test/java/BafflingBirthdaysTest.java | 218 ++-- .../src/test/java/BankAccountTest.java | 126 +-- .../src/test/java/BinarySearchTreeTest.java | 174 ++-- .../src/test/java/BinarySearchTest.java | 123 ++- .../practice/bob/src/test/java/BobTest.java | 88 +- .../src/test/java/BookStoreTest.java | 112 +- .../src/test/java/BottleSongTest.java | 233 ++--- .../src/test/java/BowlingGameTest.java | 453 +++++--- .../camicia/src/test/java/CamiciaTest.java | 455 ++++---- .../src/test/java/ChangeCalculatorTest.java | 44 +- .../src/test/java/CircularBufferTest.java | 69 +- .../src/test/java/CollatzCalculatorTest.java | 30 +- .../src/test/java/ComplexNumberTest.java | 208 ++-- .../connect/src/test/java/ConnectTest.java | 176 +--- .../src/test/java/CryptoSquareTest.java | 54 +- .../src/test/java/CustomSetTest.java | 495 ++++----- .../darts/src/test/java/DartsTest.java | 45 +- .../src/test/java/DiamondPrinterTest.java | 156 ++- .../DifferenceOfSquaresCalculatorTest.java | 89 +- .../src/test/java/DnDCharacterTest.java | 238 ++--- .../dominoes/src/test/java/DominoesTest.java | 181 ++-- .../dot-dsl/src/test/java/GraphTest.java | 81 +- .../src/test/java/EliudsEggsTest.java | 2 + .../practice/etl/src/test/java/EtlTest.java | 176 ++-- .../src/test/java/FlattenerTest.java | 137 +-- .../src/test/java/FlowerFieldBoardTest.java | 328 +++--- .../src/test/java/FoodChainTest.java | 417 +++++--- .../src/test/java/ForthEvaluatorTest.java | 366 +++---- .../src/test/java/GameOfLifeTest.java | 178 ++-- .../src/test/java/GigasecondTest.java | 43 +- .../src/test/java/GoCountingTest.java | 194 ++-- .../src/test/java/SchoolTest.java | 78 +- .../grains/src/test/java/GrainsTest.java | 96 +- .../grep/src/test/java/GrepToolTest.java | 584 +++++------ .../hamming/src/test/java/HammingTest.java | 55 +- .../src/test/java/GreeterTest.java | 5 +- .../src/test/java/HighScoresTest.java | 127 ++- .../house/src/test/java/HouseTest.java | 392 +++---- .../java/IntergalacticTransmissionTest.java | 186 ++-- .../src/test/java/IsbnVerifierTest.java | 98 +- .../src/test/java/IsogramCheckerTest.java | 78 +- .../src/test/java/KillerSudokuHelperTest.java | 168 ++- .../src/test/java/KindergartenGardenTest.java | 253 +++-- .../knapsack/src/test/java/KnapsackTest.java | 123 ++- .../LargestSeriesProductCalculatorTest.java | 112 +- .../practice/leap/src/test/java/LeapTest.java | 55 +- .../ledger/src/test/java/LedgerTest.java | 224 ++-- .../src/test/java/DoublyLinkedListTest.java | 53 +- .../list-ops/src/test/java/ListOpsTest.java | 170 ++- .../luhn/src/test/java/LuhnValidatorTest.java | 131 +-- .../markdown/src/test/java/MarkdownTest.java | 131 +-- .../src/test/java/BracketCheckerTest.java | 123 ++- .../matrix/src/test/java/MatrixTest.java | 89 +- .../meetup/src/test/java/MeetupTest.java | 478 +++++---- .../src/test/java/MicroBlogTest.java | 67 +- .../src/test/java/PrimeCalculatorTest.java | 32 +- .../src/test/java/NucleotideCounterTest.java | 64 +- .../test/java/OpticalCharacterReaderTest.java | 204 ++-- .../test/java/PalindromeCalculatorTest.java | 215 ++-- .../src/test/java/PangramCheckerTest.java | 61 +- .../java/ParallelLetterFrequencyTest.java | 656 ++++++------ .../java/PascalsTriangleGeneratorTest.java | 127 +-- .../src/test/java/NaturalNumberTest.java | 104 +- .../src/test/java/PhoneNumberTest.java | 56 +- .../src/test/java/PiecingItTogetherTest.java | 90 +- .../src/test/java/PigLatinTranslatorTest.java | 182 ++-- .../poker/src/test/java/PokerTest.java | 364 +++---- .../practice/pov/src/test/java/PovTest.java | 286 +++--- .../test/java/PrimeFactorsCalculatorTest.java | 70 +- .../prism/src/test/java/PrismTest.java | 571 +++++++---- .../src/test/java/ProteinTranslatorTest.java | 216 ++-- .../proverb/src/test/java/ProverbTest.java | 85 +- .../src/test/java/PythagoreanTripletTest.java | 159 ++- .../test/java/QueenAttackCalculatorTest.java | 165 +-- .../src/test/java/RailFenceCipherTest.java | 63 +- .../src/test/java/RaindropConverterTest.java | 92 +- .../src/test/java/RationalTest.java | 270 +++-- .../react/src/test/java/ReactTest.java | 75 +- .../src/test/java/RectangleCounterTest.java | 126 ++- .../src/test/java/RelativeDistanceTest.java | 426 ++++---- .../src/test/java/ResistorColorDuoTest.java | 69 +- .../src/test/java/ResistorColorTrioTest.java | 92 +- .../src/test/java/ResistorColorTest.java | 48 +- .../rest-api/src/test/java/RestApiTest.java | 409 ++++---- .../src/test/java/ReverseStringTest.java | 31 +- .../src/test/java/RnaTranscriptionTest.java | 39 +- .../src/test/java/RobotTest.java | 257 ++--- .../src/test/java/RomanNumeralsTest.java | 165 ++- .../src/test/java/RotationalCipherTest.java | 54 +- .../src/test/java/RunLengthEncodingTest.java | 127 ++- .../src/test/java/MatrixTest.java | 154 ++- .../src/test/java/SatelliteTest.java | 57 +- .../practice/say/src/test/java/SayTest.java | 73 +- .../src/test/java/ScrabbleScoreTest.java | 66 +- .../test/java/HandshakeCalculatorTest.java | 93 +- .../series/src/test/java/SeriesTest.java | 92 +- .../src/test/java/SgfParsingTest.java | 238 ++--- .../sieve/src/test/java/SieveTest.java | 212 +++- .../src/test/java/SimpleLinkedListTest.java | 54 +- .../space-age/src/test/java/SpaceAgeTest.java | 41 +- .../test/java/SpiralMatrixBuilderTest.java | 66 +- .../test/java/SplitSecondStopwatchTest.java | 6 +- .../src/test/java/SquareRootTest.java | 26 +- .../src/test/java/StateOfTicTacToeTest.java | 314 +++--- .../test/java/RelationshipComputerTest.java | 149 +-- .../src/test/java/SumOfMultiplesTest.java | 191 +--- .../src/test/java/SwiftSchedulingTest.java | 149 ++- .../src/test/java/TournamentTest.java | 135 +-- .../src/test/java/TransposeTest.java | 82 +- .../src/test/java/BuildTreeTest.java | 250 ++--- .../triangle/src/test/java/TriangleTest.java | 188 ++-- .../src/test/java/TwelveDaysTest.java | 330 +++--- .../src/test/java/TwoBucketTest.java | 117 ++- .../test/java/VariableLengthQuantityTest.java | 391 +++---- .../src/test/java/WordCountTest.java | 177 ++-- .../src/test/java/WordSearcherTest.java | 968 ++++++++++-------- .../src/test/java/WordProblemSolverTest.java | 120 ++- .../yacht/src/test/java/YachtTest.java | 151 +-- .../src/test/java/ZebraPuzzleTest.java | 4 + .../zipper/src/test/java/ZipperTest.java | 147 ++- 128 files changed, 11002 insertions(+), 10913 deletions(-) diff --git a/exercises/practice/acronym/src/test/java/AcronymTest.java b/exercises/practice/acronym/src/test/java/AcronymTest.java index 09b419c4a..2347f809a 100644 --- a/exercises/practice/acronym/src/test/java/AcronymTest.java +++ b/exercises/practice/acronym/src/test/java/AcronymTest.java @@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class AcronymTest { - + @Test @DisplayName("basic") public void basic() { @@ -32,7 +32,7 @@ public void punctuation() { @Disabled("Remove to run test") @Test @DisplayName("all caps word") - public void nonAcronymAllCapsWord() { + public void allCapsWord() { assertThat(new Acronym("GNU Image Manipulation Program").get()) .isEqualTo("GIMP"); } @@ -49,7 +49,8 @@ public void punctuationWithoutWhitespace() { @Test @DisplayName("very long abbreviation") public void veryLongAbbreviation() { - assertThat(new Acronym("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me").get()) + assertThat(new Acronym("Rolling On The Floor Laughing So Hard That My Dogs Came Over And " + + "Licked Me").get()) .isEqualTo("ROTFLSHTMDCOALM"); } @@ -77,5 +78,4 @@ public void underscoreEmphasis() { .isEqualTo("TRNT"); } - } diff --git a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java index 25bad1a0b..2ed6022b6 100644 --- a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java +++ b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java @@ -10,127 +10,180 @@ public class AffineCipherTest { private AffineCipher affineCipher = new AffineCipher(); @Test - @DisplayName("encode yes") - public void testEncodeYes() { - assertThat(affineCipher.encode("yes", 5, 7)).isEqualTo("xbt"); + @DisplayName("encode -> encode yes") + public void encodeEncodeYes() { + + assertThat(affineCipher.encode( + "yes", 5, 7)) + .isEqualTo("xbt"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode no") - public void testEncodeNo() { - assertThat(affineCipher.encode("no", 15, 18)).isEqualTo("fu"); + @DisplayName("encode -> encode no") + public void encodeEncodeNo() { + + assertThat(affineCipher.encode( + "no", 15, 18)) + .isEqualTo("fu"); + } @Disabled("Remove to run test") - @DisplayName("encode OMG") @Test - public void testEncodeOMG() { - assertThat(affineCipher.encode("OMG", 21, 3)).isEqualTo("lvz"); + @DisplayName("encode -> encode OMG") + public void encodeEncodeOmg() { + + assertThat(affineCipher.encode( + "OMG", 21, 3)) + .isEqualTo("lvz"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode O M G") - public void testEncodeOMGWithSpaces() { - assertThat(affineCipher.encode("O M G", 25, 47)).isEqualTo("hjp"); + @DisplayName("encode -> encode O M G") + public void encodeEncodeOMG() { + + assertThat(affineCipher.encode( + "O M G", 25, 47)) + .isEqualTo("hjp"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode mindblowingly") - public void testEncodeMindBlowingly() { - assertThat(affineCipher.encode("mindblowingly", 11, 15)).isEqualTo("rzcwa gnxzc dgt"); + @DisplayName("encode -> encode mindblowingly") + public void encodeEncodeMindblowingly() { + + assertThat(affineCipher.encode( + "mindblowingly", 11, 15)) + .isEqualTo("rzcwa gnxzc dgt"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode numbers") - public void testEncodeNumbers() { - assertThat(affineCipher.encode("Testing,1 2 3, testing.", 3, 4)) + @DisplayName("encode -> encode numbers") + public void encodeEncodeNumbers() { + + assertThat(affineCipher.encode( + "Testing,1 2 3, testing.", 3, 4)) .isEqualTo("jqgjc rw123 jqgjc rw"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode deep thought") - public void testEncodeDeepThought() { - assertThat(affineCipher.encode("Truth is fiction.", 5, 17)) + @DisplayName("encode -> encode deep thought") + public void encodeEncodeDeepThought() { + + assertThat(affineCipher.encode( + "Truth is fiction.", 5, 17)) .isEqualTo("iynia fdqfb ifje"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode all the letters") - public void testEncodeAllTheLetters() { - assertThat(affineCipher.encode("The quick brown fox jumps over the lazy dog.", 17, 33)) + @DisplayName("encode -> encode all the letters") + public void encodeEncodeAllTheLetters() { + + assertThat(affineCipher.encode( + "The quick brown fox jumps over the lazy dog.", 17, 33)) .isEqualTo("swxtj npvyk lruol iejdc blaxk swxmh qzglf"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode with a not coprime to m") - public void testEncodeThrowsMeaningfulException() { + @DisplayName("encode -> encode with a not coprime to m") + public void encodeEncodeWithANotCoprimeToM() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> affineCipher.encode("This is a test", 6, 17)) - .withMessage("Error: keyA and alphabet size must be coprime."); + .isThrownBy(() -> affineCipher.encode( + "This is a test.", 6, 17)) + .withMessage("Error: keyA and alphabet size must be coprime."); + } @Disabled("Remove to run test") @Test - @DisplayName("decode exercism") - public void testDecodeExercism() { - assertThat(affineCipher.decode("tytgn fjr", 3, 7)) + @DisplayName("decode -> decode exercism") + public void decodeDecodeExercism() { + + assertThat(affineCipher.decode( + "tytgn fjr", 3, 7)) .isEqualTo("exercism"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode a sentence") - public void testDecodeSentence() { - assertThat(affineCipher.decode("qdwju nqcro muwhn odqun oppmd aunwd o", 19, 16)) + @DisplayName("decode -> decode a sentence") + public void decodeDecodeASentence() { + + assertThat(affineCipher.decode( + "qdwju nqcro muwhn odqun oppmd aunwd o", 19, 16)) .isEqualTo("anobstacleisoftenasteppingstone"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode numbers") - public void testDecodeNumbers() { - assertThat(affineCipher.decode("odpoz ub123 odpoz ub", 25, 7)) + @DisplayName("decode -> decode numbers") + public void decodeDecodeNumbers() { + + assertThat(affineCipher.decode( + "odpoz ub123 odpoz ub", 25, 7)) .isEqualTo("testing123testing"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode all the letters") - public void testDecodeAllTheLetters() { - assertThat(affineCipher.decode("swxtj npvyk lruol iejdc blaxk swxmh qzglf", 17, 33)) + @DisplayName("decode -> decode all the letters") + public void decodeDecodeAllTheLetters() { + + assertThat(affineCipher.decode( + "swxtj npvyk lruol iejdc blaxk swxmh qzglf", 17, 33)) .isEqualTo("thequickbrownfoxjumpsoverthelazydog"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode with no spaces in input") - public void testDecodeWithNoSpaces() { - assertThat(affineCipher.decode("swxtjnpvyklruoliejdcblaxkswxmhqzglf", 17, 33)) + @DisplayName("decode -> decode with no spaces in input") + public void decodeDecodeWithNoSpacesInInput() { + + assertThat(affineCipher.decode( + "swxtjnpvyklruoliejdcblaxkswxmhqzglf", 17, 33)) .isEqualTo("thequickbrownfoxjumpsoverthelazydog"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode with too many spaces") - public void testDecodeWithTooManySpaces() { - assertThat(affineCipher.decode("vszzm cly yd cg qdp", 15, 16)) + @DisplayName("decode -> decode with too many spaces") + public void decodeDecodeWithTooManySpaces() { + + assertThat(affineCipher.decode( + "vszzm cly yd cg qdp", 15, 16)) .isEqualTo("jollygreengiant"); + } @Disabled("Remove to run test") @Test - @DisplayName("decode with a not coprime to m") - public void testDecodeThrowsMeaningfulException() { + @DisplayName("decode -> decode with a not coprime to m") + public void decodeDecodeWithANotCoprimeToM() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> affineCipher.decode("Test", 13, 5)) - .withMessage("Error: keyA and alphabet size must be coprime."); + .isThrownBy(() -> affineCipher.decode( + "Test", 13, 5)) + .withMessage("Error: keyA and alphabet size must be coprime."); + } } diff --git a/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java b/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java index c2ca95a70..dbea68bf6 100644 --- a/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java +++ b/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java @@ -9,200 +9,247 @@ public class BaseConverterTest { @Test @DisplayName("single bit one to decimal") - public void testSingleBitOneToDecimal() { - BaseConverter baseConverter = new BaseConverter(2, new int[]{1}); + public void singleBitOneToDecimal() { - assertThat(baseConverter.convertToBase(10)) + assertThat(new BaseConverter(2, new int[]{1}) + .convertToBase(10)) .containsExactly(1); + } @Disabled("Remove to run test") @Test @DisplayName("binary to single decimal") - public void testBinaryToSingleDecimal() { - BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1}); + public void binaryToSingleDecimal() { - assertThat(baseConverter.convertToBase(10)) + assertThat(new BaseConverter(2, new int[]{1, 0, 1}) + .convertToBase(10)) .containsExactly(5); + } @Disabled("Remove to run test") @Test @DisplayName("single decimal to binary") - public void testSingleDecimalToBinary() { - BaseConverter baseConverter = new BaseConverter(10, new int[]{5}); + public void singleDecimalToBinary() { - assertThat(baseConverter.convertToBase(2)) + assertThat(new BaseConverter(10, new int[]{5}) + .convertToBase(2)) .containsExactly(1, 0, 1); + } @Disabled("Remove to run test") @Test @DisplayName("binary to multiple decimal") - public void testBinaryToMultipleDecimal() { - BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}); + public void binaryToMultipleDecimal() { - assertThat(baseConverter.convertToBase(10)) + assertThat(new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}) + .convertToBase(10)) .containsExactly(4, 2); + } @Disabled("Remove to run test") @Test @DisplayName("decimal to binary") - public void testDecimalToBinary() { - BaseConverter baseConverter = new BaseConverter(10, new int[]{4, 2}); + public void decimalToBinary() { + + assertThat(new BaseConverter(10, new int[]{4, 2}) + .convertToBase(2)) + .containsExactly( + 1, + 0, + 1, + 0, + 1, + 0); - assertThat(baseConverter.convertToBase(2)) - .containsExactly(1, 0, 1, 0, 1, 0); } @Disabled("Remove to run test") @Test @DisplayName("trinary to hexadecimal") - public void testTrinaryToHexadecimal() { - BaseConverter baseConverter = new BaseConverter(3, new int[]{1, 1, 2, 0}); + public void trinaryToHexadecimal() { - assertThat(baseConverter.convertToBase(16)) + assertThat(new BaseConverter(3, new int[]{1, 1, 2, 0}) + .convertToBase(16)) .containsExactly(2, 10); + } @Disabled("Remove to run test") @Test @DisplayName("hexadecimal to trinary") - public void testHexadecimalToTrinary() { - BaseConverter baseConverter = new BaseConverter(16, new int[]{2, 10}); + public void hexadecimalToTrinary() { - assertThat(baseConverter.convertToBase(3)) + assertThat(new BaseConverter(16, new int[]{2, 10}) + .convertToBase(3)) .containsExactly(1, 1, 2, 0); + } @Disabled("Remove to run test") @Test @DisplayName("15-bit integer") public void test15BitInteger() { - BaseConverter baseConverter = new BaseConverter(97, new int[]{3, 46, 60}); - assertThat(baseConverter.convertToBase(73)) + assertThat(new BaseConverter(97, new int[]{3, 46, 60}) + .convertToBase(73)) .containsExactly(6, 10, 45); + } @Disabled("Remove to run test") @Test @DisplayName("empty list") - public void testEmptyDigits() { - BaseConverter baseConverter = new BaseConverter(2, new int[]{}); + public void emptyList() { - assertThat(baseConverter.convertToBase(10)) + assertThat(new BaseConverter(2, new int[]{}) + .convertToBase(10)) .containsExactly(0); + } @Disabled("Remove to run test") @Test @DisplayName("single zero") - public void testSingleZero() { - BaseConverter baseConverter = new BaseConverter(10, new int[]{0}); + public void singleZero() { - assertThat(baseConverter.convertToBase(2)) + assertThat(new BaseConverter(10, new int[]{0}) + .convertToBase(2)) .containsExactly(0); + } @Disabled("Remove to run test") @Test @DisplayName("multiple zeros") - public void testMultipleZeros() { - BaseConverter baseConverter = new BaseConverter(10, new int[]{0, 0, 0}); + public void multipleZeros() { - assertThat(baseConverter.convertToBase(2)) + assertThat(new BaseConverter(10, new int[]{0, 0, 0}) + .convertToBase(2)) .containsExactly(0); + } @Disabled("Remove to run test") @Test @DisplayName("leading zeros") - public void testLeadingZeros() { - BaseConverter baseConverter = new BaseConverter(7, new int[]{0, 6, 0}); + public void leadingZeros() { - assertThat(baseConverter.convertToBase(10)) + assertThat(new BaseConverter(7, new int[]{0, 6, 0}) + .convertToBase(10)) .containsExactly(4, 2); + } @Disabled("Remove to run test") @Test @DisplayName("input base is one") - public void testFirstBaseIsOne() { + public void inputBaseIsOne() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new BaseConverter(1, new int[]{0})) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(1, new int[]{0}) + .convertToBase(10)) + .withMessage("Bases must be at least 2."); + } @Disabled("Remove to run test") @Test @DisplayName("input base is zero") - public void testFirstBaseIsZero() { + public void inputBaseIsZero() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new BaseConverter(0, new int[]{})) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(0, new int[]{}) + .convertToBase(10)) + .withMessage("Bases must be at least 2."); + } @Disabled("Remove to run test") @Test @DisplayName("input base is negative") - public void testFirstBaseIsNegative() { + public void inputBaseIsNegative() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new BaseConverter(-2, new int[]{1})) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(-2, new int[]{1}) + .convertToBase(10)) + .withMessage("Bases must be at least 2."); + } @Disabled("Remove to run test") @Test @DisplayName("negative digit") - public void testNegativeDigit() { + public void negativeDigit() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new BaseConverter(2, new int[]{1, -1, 1, 0, 1, 0})) - .withMessage("Digits may not be negative."); + .isThrownBy(() -> new BaseConverter(2, new int[]{1, -1, 1, 0, 1, 0}) + .convertToBase(10)) + .withMessage("Digits may not be negative."); + } @Disabled("Remove to run test") @Test @DisplayName("invalid positive digit") - public void testInvalidPositiveDigit() { + public void invalidPositiveDigit() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new BaseConverter(2, new int[]{1, 2, 1, 0, 1, 0})) - .withMessage("All digits must be strictly less than the base."); + .isThrownBy(() -> new BaseConverter(2, new int[]{1, 2, 1, 0, 1, 0}) + .convertToBase(10)) + .withMessage("All digits must be strictly less than the base."); + } @Disabled("Remove to run test") @Test @DisplayName("output base is one") - public void testSecondBaseIsOne() { - BaseConverter baseConverter = - new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}); + public void outputBaseIsOne() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> baseConverter.convertToBase(1)) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}) + .convertToBase(1)) + .withMessage("Bases must be at least 2."); + } @Disabled("Remove to run test") @Test @DisplayName("output base is zero") - public void testSecondBaseIsZero() { - BaseConverter baseConverter = new BaseConverter(10, new int[]{7}); + public void outputBaseIsZero() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> baseConverter.convertToBase(0)) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(10, new int[]{7}) + .convertToBase(0)) + .withMessage("Bases must be at least 2."); + } @Disabled("Remove to run test") @Test @DisplayName("output base is negative") - public void testSecondBaseIsNegative() { - BaseConverter baseConverter = new BaseConverter(2, new int[]{1}); + public void outputBaseIsNegative() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> baseConverter.convertToBase(-7)) - .withMessage("Bases must be at least 2."); + .isThrownBy(() -> new BaseConverter(2, new int[]{1}) + .convertToBase(-7)) + .withMessage("Bases must be at least 2."); + + } + + @Disabled("Remove to run test") + @Test + @DisplayName("both bases are negative") + public void bothBasesAreNegative() { + + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new BaseConverter(-2, new int[]{1}) + .convertToBase(-7)) + .withMessage("Bases must be at least 2."); + } } diff --git a/exercises/practice/allergies/src/test/java/AllergiesTest.java b/exercises/practice/allergies/src/test/java/AllergiesTest.java index cd0ae5cf7..e540e9f28 100644 --- a/exercises/practice/allergies/src/test/java/AllergiesTest.java +++ b/exercises/practice/allergies/src/test/java/AllergiesTest.java @@ -6,455 +6,378 @@ public class AllergiesTest { - - // Testing for eggs allergy - @Test - @DisplayName("not allergic to anything") - public void eggsNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.EGGS)).isFalse(); + @DisplayName("testing for eggs allergy -> not allergic to anything") + public void testingForEggsAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.EGGS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to eggs") - public void eggsAllergicOnlyToEggs() { - Allergies allergies = new Allergies(1); - - assertThat(allergies.isAllergicTo(Allergen.EGGS)).isTrue(); + @DisplayName("testing for eggs allergy -> allergic only to eggs") + public void testingForEggsAllergyAllergicOnlyToEggs() { + assertThat(new Allergies(1).isAllergicTo(Allergen.EGGS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to eggs and something else") - public void eggsAllergicToEggsAndSomethingElse() { - Allergies allergies = new Allergies(3); - - assertThat(allergies.isAllergicTo(Allergen.EGGS)).isTrue(); + @DisplayName("testing for eggs allergy -> allergic to eggs and something else") + public void testingForEggsAllergyAllergicToEggsAndSomethingElse() { + assertThat(new Allergies(3).isAllergicTo(Allergen.EGGS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not eggs") - public void eggsAllergicToSomethingButNotEggs() { - Allergies allergies = new Allergies(2); - - assertThat(allergies.isAllergicTo(Allergen.EGGS)).isFalse(); + @DisplayName("testing for eggs allergy -> allergic to something, but not eggs") + public void testingForEggsAllergyAllergicToSomethingButNotEggs() { + assertThat(new Allergies(2).isAllergicTo(Allergen.EGGS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void eggsAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.EGGS)).isTrue(); + @DisplayName("testing for eggs allergy -> allergic to everything") + public void testingForEggsAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.EGGS)) + .isTrue(); } - - // Testing for peanuts allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void peanutsNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.PEANUTS)).isFalse(); + @DisplayName("testing for peanuts allergy -> not allergic to anything") + public void testingForPeanutsAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.PEANUTS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to peanuts") - public void peanutsAllergicOnlyToPeanuts() { - Allergies allergies = new Allergies(2); - - assertThat(allergies.isAllergicTo(Allergen.PEANUTS)).isTrue(); + @DisplayName("testing for peanuts allergy -> allergic only to peanuts") + public void testingForPeanutsAllergyAllergicOnlyToPeanuts() { + assertThat(new Allergies(2).isAllergicTo(Allergen.PEANUTS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to peanuts and something else") - public void peanutsAllergicToPeanutsAndSomethingElse() { - Allergies allergies = new Allergies(7); - - assertThat(allergies.isAllergicTo(Allergen.PEANUTS)).isTrue(); + @DisplayName("testing for peanuts allergy -> allergic to peanuts and something else") + public void testingForPeanutsAllergyAllergicToPeanutsAndSomethingElse() { + assertThat(new Allergies(7).isAllergicTo(Allergen.PEANUTS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not peanuts") - public void peanutsAllergicToSomethingButNotPeanuts() { - Allergies allergies = new Allergies(5); - - assertThat(allergies.isAllergicTo(Allergen.PEANUTS)).isFalse(); + @DisplayName("testing for peanuts allergy -> allergic to something, but not peanuts") + public void testingForPeanutsAllergyAllergicToSomethingButNotPeanuts() { + assertThat(new Allergies(5).isAllergicTo(Allergen.PEANUTS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void peanutsAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.PEANUTS)).isTrue(); + @DisplayName("testing for peanuts allergy -> allergic to everything") + public void testingForPeanutsAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.PEANUTS)) + .isTrue(); } - - // Testing for shellfish allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void shellfishNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.SHELLFISH)).isFalse(); + @DisplayName("testing for shellfish allergy -> not allergic to anything") + public void testingForShellfishAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.SHELLFISH)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to shellfish") - public void shellfishAllergicOnlyToShellfish() { - Allergies allergies = new Allergies(4); - - assertThat(allergies.isAllergicTo(Allergen.SHELLFISH)).isTrue(); + @DisplayName("testing for shellfish allergy -> allergic only to shellfish") + public void testingForShellfishAllergyAllergicOnlyToShellfish() { + assertThat(new Allergies(4).isAllergicTo(Allergen.SHELLFISH)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to shellfish and something else") - public void shellfishAllergicToShellfishAndSomethingElse() { - Allergies allergies = new Allergies(14); - - assertThat(allergies.isAllergicTo(Allergen.SHELLFISH)).isTrue(); + @DisplayName("testing for shellfish allergy -> allergic to shellfish and something else") + public void testingForShellfishAllergyAllergicToShellfishAndSomethingElse() { + assertThat(new Allergies(14).isAllergicTo(Allergen.SHELLFISH)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not shellfish") - public void shellfishAllergicToSomethingButNotShellfish() { - Allergies allergies = new Allergies(10); - - assertThat(allergies.isAllergicTo(Allergen.SHELLFISH)).isFalse(); + @DisplayName("testing for shellfish allergy -> allergic to something, but not shellfish") + public void testingForShellfishAllergyAllergicToSomethingButNotShellfish() { + assertThat(new Allergies(10).isAllergicTo(Allergen.SHELLFISH)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void shellfishAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.SHELLFISH)).isTrue(); + @DisplayName("testing for shellfish allergy -> allergic to everything") + public void testingForShellfishAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.SHELLFISH)) + .isTrue(); } - - // Testing for strawberries allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void strawberriesNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.STRAWBERRIES)).isFalse(); + @DisplayName("testing for strawberries allergy -> not allergic to anything") + public void testingForStrawberriesAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.STRAWBERRIES)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to strawberries") - public void strawberriesAllergicOnlyToStrawberries() { - Allergies allergies = new Allergies(8); - - assertThat(allergies.isAllergicTo(Allergen.STRAWBERRIES)).isTrue(); + @DisplayName("testing for strawberries allergy -> allergic only to strawberries") + public void testingForStrawberriesAllergyAllergicOnlyToStrawberries() { + assertThat(new Allergies(8).isAllergicTo(Allergen.STRAWBERRIES)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to strawberries and something else") - public void strawberriesAllergicToStrawberriesAndSomethingElse() { - Allergies allergies = new Allergies(28); - - assertThat(allergies.isAllergicTo(Allergen.STRAWBERRIES)).isTrue(); + @DisplayName("testing for strawberries allergy -> allergic to strawberries and something else") + public void testingForStrawberriesAllergyAllergicToStrawberriesAndSomethingEl() { + assertThat(new Allergies(28).isAllergicTo(Allergen.STRAWBERRIES)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not strawberries") - public void strawberriesAllergicToSomethingButNotStrawberries() { - Allergies allergies = new Allergies(20); - - assertThat(allergies.isAllergicTo(Allergen.STRAWBERRIES)).isFalse(); + @DisplayName("testing for strawberries allergy -> allergic to something, but not strawberries") + public void testingForStrawberriesAllergyAllergicToSomethingButNotStrawberrie() { + assertThat(new Allergies(20).isAllergicTo(Allergen.STRAWBERRIES)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void strawberriesAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.STRAWBERRIES)).isTrue(); + @DisplayName("testing for strawberries allergy -> allergic to everything") + public void testingForStrawberriesAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.STRAWBERRIES)) + .isTrue(); } - - // Testing for tomatoes allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void tomatoesNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.TOMATOES)).isFalse(); + @DisplayName("testing for tomatoes allergy -> not allergic to anything") + public void testingForTomatoesAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.TOMATOES)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to tomatoes") - public void tomatoesAllergicOnlyToTomatoes() { - Allergies allergies = new Allergies(16); - - assertThat(allergies.isAllergicTo(Allergen.TOMATOES)).isTrue(); + @DisplayName("testing for tomatoes allergy -> allergic only to tomatoes") + public void testingForTomatoesAllergyAllergicOnlyToTomatoes() { + assertThat(new Allergies(16).isAllergicTo(Allergen.TOMATOES)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to tomatoes and something else") - public void tomatoesAllergicToTomatoesAndSomethingElse() { - Allergies allergies = new Allergies(56); - - assertThat(allergies.isAllergicTo(Allergen.TOMATOES)).isTrue(); + @DisplayName("testing for tomatoes allergy -> allergic to tomatoes and something else") + public void testingForTomatoesAllergyAllergicToTomatoesAndSomethingElse() { + assertThat(new Allergies(56).isAllergicTo(Allergen.TOMATOES)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not tomatoes") - public void tomatoesAllergicToSomethingButNotTomatoes() { - Allergies allergies = new Allergies(40); - - assertThat(allergies.isAllergicTo(Allergen.TOMATOES)).isFalse(); + @DisplayName("testing for tomatoes allergy -> allergic to something, but not tomatoes") + public void testingForTomatoesAllergyAllergicToSomethingButNotTomatoes() { + assertThat(new Allergies(40).isAllergicTo(Allergen.TOMATOES)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void tomatoesAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.TOMATOES)).isTrue(); + @DisplayName("testing for tomatoes allergy -> allergic to everything") + public void testingForTomatoesAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.TOMATOES)) + .isTrue(); } - - // Testing for chocolate allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void chocolateNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.CHOCOLATE)).isFalse(); + @DisplayName("testing for chocolate allergy -> not allergic to anything") + public void testingForChocolateAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.CHOCOLATE)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to chocolate") - public void chocolateAllergicOnlyToChocolate() { - Allergies allergies = new Allergies(32); - - assertThat(allergies.isAllergicTo(Allergen.CHOCOLATE)).isTrue(); + @DisplayName("testing for chocolate allergy -> allergic only to chocolate") + public void testingForChocolateAllergyAllergicOnlyToChocolate() { + assertThat(new Allergies(32).isAllergicTo(Allergen.CHOCOLATE)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to chocolate and something else") - public void chocolateAllergicToChocolateAndSomethingElse() { - Allergies allergies = new Allergies(112); - - assertThat(allergies.isAllergicTo(Allergen.CHOCOLATE)).isTrue(); + @DisplayName("testing for chocolate allergy -> allergic to chocolate and something else") + public void testingForChocolateAllergyAllergicToChocolateAndSomethingElse() { + assertThat(new Allergies(112).isAllergicTo(Allergen.CHOCOLATE)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not chocolate") - public void chocolateAllergicToSomethingButNotChocolate() { - Allergies allergies = new Allergies(80); - - assertThat(allergies.isAllergicTo(Allergen.CHOCOLATE)).isFalse(); + @DisplayName("testing for chocolate allergy -> allergic to something, but not chocolate") + public void testingForChocolateAllergyAllergicToSomethingButNotChocolate() { + assertThat(new Allergies(80).isAllergicTo(Allergen.CHOCOLATE)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void chocolateAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.CHOCOLATE)).isTrue(); + @DisplayName("testing for chocolate allergy -> allergic to everything") + public void testingForChocolateAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.CHOCOLATE)) + .isTrue(); } - - // Testing for pollen allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void pollenNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.POLLEN)).isFalse(); + @DisplayName("testing for pollen allergy -> not allergic to anything") + public void testingForPollenAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.POLLEN)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to pollen") - public void pollenAllergicOnlyToPollen() { - Allergies allergies = new Allergies(64); - - assertThat(allergies.isAllergicTo(Allergen.POLLEN)).isTrue(); + @DisplayName("testing for pollen allergy -> allergic only to pollen") + public void testingForPollenAllergyAllergicOnlyToPollen() { + assertThat(new Allergies(64).isAllergicTo(Allergen.POLLEN)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to pollen and something else") - public void pollenAllergicToPollenAndSomethingElse() { - Allergies allergies = new Allergies(224); - - assertThat(allergies.isAllergicTo(Allergen.POLLEN)).isTrue(); + @DisplayName("testing for pollen allergy -> allergic to pollen and something else") + public void testingForPollenAllergyAllergicToPollenAndSomethingElse() { + assertThat(new Allergies(224).isAllergicTo(Allergen.POLLEN)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not pollen") - public void pollenAllergicToSomethingButNotPollen() { - Allergies allergies = new Allergies(160); - - assertThat(allergies.isAllergicTo(Allergen.POLLEN)).isFalse(); + @DisplayName("testing for pollen allergy -> allergic to something, but not pollen") + public void testingForPollenAllergyAllergicToSomethingButNotPollen() { + assertThat(new Allergies(160).isAllergicTo(Allergen.POLLEN)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void pollenAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.POLLEN)).isTrue(); + @DisplayName("testing for pollen allergy -> allergic to everything") + public void testingForPollenAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.POLLEN)) + .isTrue(); } - - // Testing for cats allergy - + @Disabled("Remove to run test") @Test - @DisplayName("not allergic to anything") - public void catsNotAllergicToAnything() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.isAllergicTo(Allergen.CATS)).isFalse(); + @DisplayName("testing for cats allergy -> not allergic to anything") + public void testingForCatsAllergyNotAllergicToAnything() { + assertThat(new Allergies(0).isAllergicTo(Allergen.CATS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic only to cats") - public void catsAllergicOnlyToCats() { - Allergies allergies = new Allergies(128); - - assertThat(allergies.isAllergicTo(Allergen.CATS)).isTrue(); + @DisplayName("testing for cats allergy -> allergic only to cats") + public void testingForCatsAllergyAllergicOnlyToCats() { + assertThat(new Allergies(128).isAllergicTo(Allergen.CATS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to cats and something else") - public void catsAllergicToCatsAndSomethingElse() { - Allergies allergies = new Allergies(192); - - assertThat(allergies.isAllergicTo(Allergen.CATS)).isTrue(); + @DisplayName("testing for cats allergy -> allergic to cats and something else") + public void testingForCatsAllergyAllergicToCatsAndSomethingElse() { + assertThat(new Allergies(192).isAllergicTo(Allergen.CATS)) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to something, but not cats") - public void catsAllergicToSomethingButNotCats() { - Allergies allergies = new Allergies(64); - - assertThat(allergies.isAllergicTo(Allergen.CATS)).isFalse(); + @DisplayName("testing for cats allergy -> allergic to something, but not cats") + public void testingForCatsAllergyAllergicToSomethingButNotCats() { + assertThat(new Allergies(64).isAllergicTo(Allergen.CATS)) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("allergic to everything") - public void catsAllergicToEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.isAllergicTo(Allergen.CATS)).isTrue(); + @DisplayName("testing for cats allergy -> allergic to everything") + public void testingForCatsAllergyAllergicToEverything() { + assertThat(new Allergies(255).isAllergicTo(Allergen.CATS)) + .isTrue(); } - - // Testing listing allergies - @Disabled("Remove to run test") @Test - @DisplayName("no allergies") - public void listNoAllergies() { - Allergies allergies = new Allergies(0); - - assertThat(allergies.getList().size()).isEqualTo(0); + @DisplayName("list when: -> no allergies") + public void listWhenNoAllergies() { + assertThat(new Allergies(0).getList()) + .isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("just eggs") - public void listJustEggs() { - Allergies allergies = new Allergies(1); - - assertThat(allergies.getList()) + @DisplayName("list when: -> just eggs") + public void listWhenJustEggs() { + assertThat(new Allergies(1).getList()) .containsExactly(Allergen.EGGS); } @Disabled("Remove to run test") @Test - @DisplayName("just peanuts") - public void listJustPeanuts() { - Allergies allergies = new Allergies(2); - - assertThat(allergies.getList()) + @DisplayName("list when: -> just peanuts") + public void listWhenJustPeanuts() { + assertThat(new Allergies(2).getList()) .containsExactly(Allergen.PEANUTS); } @Disabled("Remove to run test") @Test - @DisplayName("just strawberries") - public void listJustStrawberries() { - Allergies allergies = new Allergies(8); - - assertThat(allergies.getList()) + @DisplayName("list when: -> just strawberries") + public void listWhenJustStrawberries() { + assertThat(new Allergies(8).getList()) .containsExactly(Allergen.STRAWBERRIES); } @Disabled("Remove to run test") @Test - @DisplayName("eggs and peanuts") - public void listEggsAndPeanuts() { - Allergies allergies = new Allergies(3); - - assertThat(allergies.getList()) - .containsExactly( - Allergen.EGGS, - Allergen.PEANUTS); + @DisplayName("list when: -> eggs and peanuts") + public void listWhenEggsAndPeanuts() { + assertThat(new Allergies(3).getList()) + .containsExactly(Allergen.EGGS, Allergen.PEANUTS); } @Disabled("Remove to run test") @Test - @DisplayName("more than eggs but not peanuts") - public void listoMoreThanEggsButNotPeanuts() { - Allergies allergies = new Allergies(5); - - assertThat(allergies.getList()) - .containsExactly( - Allergen.EGGS, - Allergen.SHELLFISH); + @DisplayName("list when: -> more than eggs but not peanuts") + public void listWhenMoreThanEggsButNotPeanuts() { + assertThat(new Allergies(5).getList()) + .containsExactly(Allergen.EGGS, Allergen.SHELLFISH); } @Disabled("Remove to run test") @Test - @DisplayName("lots of stuff") - public void listManyAllergies() { - Allergies allergies = new Allergies(248); - - assertThat(allergies.getList()) + @DisplayName("list when: -> lots of stuff") + public void listWhenLotsOfStuff() { + assertThat(new Allergies(248).getList()) .containsExactly( Allergen.STRAWBERRIES, Allergen.TOMATOES, @@ -465,11 +388,9 @@ public void listManyAllergies() { @Disabled("Remove to run test") @Test - @DisplayName("everything") - public void listEverything() { - Allergies allergies = new Allergies(255); - - assertThat(allergies.getList()) + @DisplayName("list when: -> everything") + public void listWhenEverything() { + assertThat(new Allergies(255).getList()) .containsExactly( Allergen.EGGS, Allergen.PEANUTS, @@ -483,11 +404,9 @@ public void listEverything() { @Disabled("Remove to run test") @Test - @DisplayName("no allergen score parts") - public void listNoAllergenScoreParts() { - Allergies allergies = new Allergies(509); - - assertThat(allergies.getList()) + @DisplayName("list when: -> no allergen score parts") + public void listWhenNoAllergenScoreParts() { + assertThat(new Allergies(509).getList()) .containsExactly( Allergen.EGGS, Allergen.SHELLFISH, @@ -500,11 +419,10 @@ public void listNoAllergenScoreParts() { @Disabled("Remove to run test") @Test - @DisplayName("no allergen score parts without highest valid score") - public void listNoAllergenScorePartsWithoutHighestValidScore() { - Allergies allergies = new Allergies(257); - - assertThat(allergies.getList()) + @DisplayName("list when: -> no allergen score parts without highest valid score") + public void listWhenNoAllergenScorePartsWithoutHighestValidScore() { + assertThat(new Allergies(257).getList()) .containsExactly(Allergen.EGGS); } + } diff --git a/exercises/practice/alphametics/src/test/java/AlphameticsTest.java b/exercises/practice/alphametics/src/test/java/AlphameticsTest.java index 8661a8de3..142b3b411 100644 --- a/exercises/practice/alphametics/src/test/java/AlphameticsTest.java +++ b/exercises/practice/alphametics/src/test/java/AlphameticsTest.java @@ -2,6 +2,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.Map; + import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -10,92 +12,108 @@ public class AlphameticsTest { @Test @DisplayName("puzzle with three letters") - public void testThreeLetters() throws UnsolvablePuzzleException { + public void puzzleWithThreeLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("I + BB == ILL").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('I', 1), entry('B', 9), - entry('L', 0)); + entry('L', 0) + )); + } @Disabled("Remove to run test") @Test @DisplayName("solution must have unique value for each letter") - public void testUniqueValue() { - Alphametics alphametics = new Alphametics("A == B"); + public void solutionMustHaveUniqueValueForEachLetter() throws UnsolvablePuzzleException { assertThatExceptionOfType(UnsolvablePuzzleException.class) - .isThrownBy(alphametics::solve); + .isThrownBy(() -> new Alphametics("A == B").solve()); + } @Disabled("Remove to run test") @Test @DisplayName("leading zero solution is invalid") - public void testLeadingZero() { - Alphametics alphametics = new Alphametics("ACA + DD == BD"); + public void leadingZeroSolutionIsInvalid() throws UnsolvablePuzzleException { assertThatExceptionOfType(UnsolvablePuzzleException.class) - .isThrownBy(alphametics::solve); + .isThrownBy(() -> new Alphametics("ACA + DD == BD").solve()); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with two digits final carry") - public void testTwoDigitsFinalCarry() throws UnsolvablePuzzleException { + public void puzzleWithTwoDigitsFinalCarry() throws UnsolvablePuzzleException { + assertThat(new Alphametics("A + A + A + A + A + A + A + A + A + A + A + B == BCC").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('A', 9), entry('B', 1), - entry('C', 0)); + entry('C', 0) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with four letters") - public void testFourLetters() throws UnsolvablePuzzleException { + public void puzzleWithFourLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("AS + A == MOM").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('A', 9), entry('S', 2), entry('M', 1), - entry('O', 0)); + entry('O', 0) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with six letters") - public void testSixLetters() throws UnsolvablePuzzleException { + public void puzzleWithSixLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("NO + NO + TOO == LATE").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('N', 7), entry('O', 4), entry('T', 9), entry('L', 1), entry('A', 0), - entry('E', 2)); + entry('E', 2) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with seven letters") - public void testSevenLetters() throws UnsolvablePuzzleException { + public void puzzleWithSevenLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("HE + SEES + THE == LIGHT").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('E', 4), entry('G', 2), entry('H', 5), entry('I', 0), entry('L', 1), entry('S', 9), - entry('T', 7)); + entry('T', 7) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with eight letters") - public void testEightLetters() throws UnsolvablePuzzleException { + public void puzzleWithEightLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("SEND + MORE == MONEY").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('S', 9), entry('E', 5), entry('N', 6), @@ -103,15 +121,18 @@ public void testEightLetters() throws UnsolvablePuzzleException { entry('M', 1), entry('O', 0), entry('R', 8), - entry('Y', 2)); + entry('Y', 2) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with ten letters") - public void testTenLetters() throws UnsolvablePuzzleException { + public void puzzleWithTenLetters() throws UnsolvablePuzzleException { + assertThat(new Alphametics("AND + A + STRONG + OFFENSE + AS + A + GOOD == DEFENSE").solve()) - .containsOnly( + .isEqualTo(Map.ofEntries( entry('A', 5), entry('D', 3), entry('E', 4), @@ -121,30 +142,38 @@ public void testTenLetters() throws UnsolvablePuzzleException { entry('O', 2), entry('R', 1), entry('S', 6), - entry('T', 9)); + entry('T', 9) + )); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with ten letters and 199 addends") - public void testTenLetters199Addends() throws UnsolvablePuzzleException { - assertThat(new Alphametics("THIS + A + FIRE + THEREFORE + FOR + ALL + HISTORIES + I + TELL + A + " + - "TALE + THAT + FALSIFIES + ITS + TITLE + TIS + A + LIE + THE + TALE + OF + THE + LAST + FIRE + " + - "HORSES + LATE + AFTER + THE + FIRST + FATHERS + FORESEE + THE + HORRORS + THE + LAST + FREE + " + - "TROLL + TERRIFIES + THE + HORSES + OF + FIRE + THE + TROLL + RESTS + AT + THE + HOLE + OF + " + - "LOSSES + IT + IS + THERE + THAT + SHE + STORES + ROLES + OF + LEATHERS + AFTER + SHE + SATISFIES + " + - "HER + HATE + OFF + THOSE + FEARS + A + TASTE + RISES + AS + SHE + HEARS + THE + LEAST + FAR + " + - "HORSE + THOSE + FAST + HORSES + THAT + FIRST + HEAR + THE + TROLL + FLEE + OFF + TO + THE + " + - "FOREST + THE + HORSES + THAT + ALERTS + RAISE + THE + STARES + OF + THE + OTHERS + AS + THE + " + - "TROLL + ASSAILS + AT + THE + TOTAL + SHIFT + HER + TEETH + TEAR + HOOF + OFF + TORSO + AS + THE + " + - "LAST + HORSE + FORFEITS + ITS + LIFE + THE + FIRST + FATHERS + HEAR + OF + THE + HORRORS + THEIR + " + - "FEARS + THAT + THE + FIRES + FOR + THEIR + FEASTS + ARREST + AS + THE + FIRST + FATHERS + " + - "RESETTLE + THE + LAST + OF + THE + FIRE + HORSES + THE + LAST + TROLL + HARASSES + THE + FOREST + " + - "HEART + FREE + AT + LAST + OF + THE + LAST + TROLL + ALL + OFFER + THEIR + FIRE + HEAT + TO + THE + " + - "ASSISTERS + FAR + OFF + THE + TROLL + FASTS + ITS + LIFE + SHORTER + AS + STARS + RISE + THE + " + - "HORSES + REST + SAFE + AFTER + ALL + SHARE + HOT + FISH + AS + THEIR + AFFILIATES + TAILOR + A + " + - "ROOFS + FOR + THEIR + SAFE == FORTRESSES").solve()) - .containsOnly( + public void puzzleWithTenLettersAnd199Addends() throws UnsolvablePuzzleException { + + assertThat(new Alphametics("THIS + A + FIRE + THEREFORE + FOR + ALL + HISTORIES + I + TELL + A + " + + "TALE + THAT + FALSIFIES + ITS + TITLE + TIS + A + LIE + THE + TALE + " + + "OF + THE + LAST + FIRE + HORSES + LATE + AFTER + THE + FIRST + FATHERS " + + "+ FORESEE + THE + HORRORS + THE + LAST + FREE + TROLL + TERRIFIES + " + + "THE + HORSES + OF + FIRE + THE + TROLL + RESTS + AT + THE + HOLE + OF " + + "+ LOSSES + IT + IS + THERE + THAT + SHE + STORES + ROLES + OF + " + + "LEATHERS + AFTER + SHE + SATISFIES + HER + HATE + OFF + THOSE + FEARS " + + "+ A + TASTE + RISES + AS + SHE + HEARS + THE + LEAST + FAR + HORSE + " + + "THOSE + FAST + HORSES + THAT + FIRST + HEAR + THE + TROLL + FLEE + OFF " + + "+ TO + THE + FOREST + THE + HORSES + THAT + ALERTS + RAISE + THE + " + + "STARES + OF + THE + OTHERS + AS + THE + TROLL + ASSAILS + AT + THE + " + + "TOTAL + SHIFT + HER + TEETH + TEAR + HOOF + OFF + TORSO + AS + THE + " + + "LAST + HORSE + FORFEITS + ITS + LIFE + THE + FIRST + FATHERS + HEAR + " + + "OF + THE + HORRORS + THEIR + FEARS + THAT + THE + FIRES + FOR + THEIR " + + "+ FEASTS + ARREST + AS + THE + FIRST + FATHERS + RESETTLE + THE + LAST " + + "+ OF + THE + FIRE + HORSES + THE + LAST + TROLL + HARASSES + THE + " + + "FOREST + HEART + FREE + AT + LAST + OF + THE + LAST + TROLL + ALL + " + + "OFFER + THEIR + FIRE + HEAT + TO + THE + ASSISTERS + FAR + OFF + THE + " + + "TROLL + FASTS + ITS + LIFE + SHORTER + AS + STARS + RISE + THE + " + + "HORSES + REST + SAFE + AFTER + ALL + SHARE + HOT + FISH + AS + THEIR + " + + "AFFILIATES + TAILOR + A + ROOFS + FOR + THEIR + SAFE == FORTRESSES").solve()) + .isEqualTo(Map.ofEntries( entry('A', 1), entry('E', 0), entry('F', 5), @@ -154,6 +183,9 @@ public void testTenLetters199Addends() throws UnsolvablePuzzleException { entry('O', 6), entry('R', 3), entry('S', 4), - entry('T', 9)); + entry('T', 9) + )); + } + } diff --git a/exercises/practice/anagram/src/test/java/AnagramTest.java b/exercises/practice/anagram/src/test/java/AnagramTest.java index 79a3a261b..46440d3d8 100644 --- a/exercises/practice/anagram/src/test/java/AnagramTest.java +++ b/exercises/practice/anagram/src/test/java/AnagramTest.java @@ -2,8 +2,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -11,196 +10,152 @@ public class AnagramTest { @Test @DisplayName("no matches") - public void testNoMatches() { - Anagram detector = new Anagram("diaper"); - - assertThat( - detector.match( - Arrays.asList("hello", "world", "zombies", "pants"))) - .isEmpty(); + public void noMatches() { + assertThat(new Anagram("diaper").match(List.of("hello", "world", "zombies", "pants"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("detects two anagrams") - public void testDetectsTwoAnagrams() { - Anagram detector = new Anagram("solemn"); - - assertThat(detector.match(Arrays.asList("lemons", "cherry", "melons"))) - .containsExactlyInAnyOrder("lemons", "melons"); + public void detectsTwoAnagrams() { + assertThat(new Anagram("solemn").match(List.of("lemons", "cherry", "melons"))) + .containsExactlyInAnyOrderElementsOf(List.of("lemons", "melons")); } @Disabled("Remove to run test") @Test @DisplayName("does not detect anagram subsets") - public void testEliminateAnagramSubsets() { - Anagram detector = new Anagram("good"); - - assertThat(detector.match(Arrays.asList("dog", "goody"))).isEmpty(); + public void doesNotDetectAnagramSubsets() { + assertThat(new Anagram("good").match(List.of("dog", "goody"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("detects anagram") - public void testDetectLongerAnagram() { - Anagram detector = new Anagram("listen"); - - assertThat( - detector.match( - Arrays.asList("enlists", "google", "inlets", "banana"))) - .containsExactlyInAnyOrder("inlets"); + public void detectsAnagram() { + assertThat(new Anagram("listen").match(List.of("enlists", "google", "inlets", "banana"))) + .containsExactlyInAnyOrderElementsOf(List.of("inlets")); } @Disabled("Remove to run test") @Test @DisplayName("detects three anagrams") - public void testDetectMultipleAnagramsForLongerWord() { - Anagram detector = new Anagram("allergy"); - assertThat( - detector.match( - Arrays.asList( - "gallery", - "ballerina", - "regally", - "clergy", - "largely", - "leading"))) - .containsExactlyInAnyOrder("gallery", "regally", "largely"); + public void detectsThreeAnagrams() { + assertThat(new Anagram("allergy").match(List.of( + "gallery", + "ballerina", + "regally", + "clergy", + "largely", + "leading" + ))) + .containsExactlyInAnyOrderElementsOf(List.of("gallery", "regally", "largely")); } @Disabled("Remove to run test") @Test @DisplayName("detects multiple anagrams with different case") - public void testDetectsMultipleAnagramsWithDifferentCase() { - Anagram detector = new Anagram("nose"); - - assertThat(detector.match(Arrays.asList("Eons", "ONES"))) - .containsExactlyInAnyOrder("Eons", "ONES"); + public void detectsMultipleAnagramsWithDifferentCase() { + assertThat(new Anagram("nose").match(List.of("Eons", "ONES"))) + .containsExactlyInAnyOrderElementsOf(List.of("Eons", "ONES")); } @Disabled("Remove to run test") @Test @DisplayName("does not detect non-anagrams with identical checksum") - public void testEliminateAnagramsWithSameChecksum() { - Anagram detector = new Anagram("mass"); - - assertThat(detector.match(Collections.singletonList("last"))) - .isEmpty(); + public void doesNotDetectNonAnagramsWithIdenticalChecksum() { + assertThat(new Anagram("mass").match(List.of("last"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("detects anagrams case-insensitively") - public void testCaseInsensitiveWhenBothAnagramAndSubjectStartWithUpperCaseLetter() { - Anagram detector = new Anagram("Orchestra"); - - assertThat( - detector.match( - Arrays.asList("cashregister", "Carthorse", "radishes"))) - .containsExactlyInAnyOrder("Carthorse"); + public void detectsAnagramsCaseInsensitively() { + assertThat(new Anagram("Orchestra").match(List.of("cashregister", "Carthorse", "radishes"))) + .containsExactlyInAnyOrderElementsOf(List.of("Carthorse")); } @Disabled("Remove to run test") @Test @DisplayName("detects anagrams using case-insensitive subject") - public void testCaseInsensitiveWhenSubjectStartsWithUpperCaseLetter() { - Anagram detector = new Anagram("Orchestra"); - - assertThat( - detector.match( - Arrays.asList("cashregister", "carthorse", "radishes"))) - .containsExactlyInAnyOrder("carthorse"); + public void detectsAnagramsUsingCaseInsensitiveSubject() { + assertThat(new Anagram("Orchestra").match(List.of("cashregister", "carthorse", "radishes"))) + .containsExactlyInAnyOrderElementsOf(List.of("carthorse")); } @Disabled("Remove to run test") @Test @DisplayName("detects anagrams using case-insensitive possible matches") - public void testCaseInsensitiveWhenAnagramStartsWithUpperCaseLetter() { - Anagram detector = new Anagram("orchestra"); - - assertThat( - detector.match( - Arrays.asList("cashregister", "Carthorse", "radishes"))) - .containsExactlyInAnyOrder("Carthorse"); + public void detectsAnagramsUsingCaseInsensitivePossibleMatches() { + assertThat(new Anagram("orchestra").match(List.of("cashregister", "Carthorse", "radishes"))) + .containsExactlyInAnyOrderElementsOf(List.of("Carthorse")); } @Disabled("Remove to run test") @Test @DisplayName("does not detect an anagram if the original word is repeated") - public void testIdenticalWordRepeatedIsNotAnagram() { - Anagram detector = new Anagram("go"); - - assertThat(detector.match(Collections.singletonList("goGoGO"))) - .isEmpty(); + public void doesNotDetectAnAnagramIfTheOriginalWordIsRepeated() { + assertThat(new Anagram("go").match(List.of("goGoGO"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("anagrams must use all letters exactly once") - public void testAnagramMustUseAllLettersExactlyOnce() { - Anagram detector = new Anagram("tapper"); - - assertThat(detector.match(Collections.singletonList("patter"))) - .isEmpty(); + public void anagramsMustUseAllLettersExactlyOnce() { + assertThat(new Anagram("tapper").match(List.of("patter"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("words are not anagrams of themselves") - public void testWordsAreNotAnagramsOfThemselvesCaseInsensitive() { - Anagram detector = new Anagram("BANANA"); - - assertThat(detector.match(Collections.singletonList("BANANA"))) - .isEmpty(); + public void wordsAreNotAnagramsOfThemselves() { + assertThat(new Anagram("BANANA").match(List.of("BANANA"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("words are not anagrams of themselves even if letter case is partially different") - public void testWordsAreNotAnagramsOfThemselvesEvenIfLetterCaseIsPartiallyDifferent() { - Anagram detector = new Anagram("BANANA"); - - assertThat(detector.match(Collections.singletonList("Banana"))) - .isEmpty(); + public void wordsAreNotAnagramsOfThemselvesEvenIfLetterCaseIsPartiallyDiffere() { + assertThat(new Anagram("BANANA").match(List.of("Banana"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("words are not anagrams of themselves even if letter case is completely different") - public void testWordsAreNotAnagramsOfThemselvesEvenIfLetterCaseIsCompletelyDifferent() { - Anagram detector = new Anagram("BANANA"); - - assertThat(detector.match(Collections.singletonList("banana"))) - .isEmpty(); + public void wordsAreNotAnagramsOfThemselvesEvenIfLetterCaseIsCompletelyDiffer() { + assertThat(new Anagram("BANANA").match(List.of("banana"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("words other than themselves can be anagrams") - public void testWordsOtherThanThemselvesCanBeAnagrams() { - Anagram detector = new Anagram("LISTEN"); - - assertThat(detector.match(Arrays.asList("LISTEN", "Silent"))) - .containsExactlyInAnyOrder("Silent"); + public void wordsOtherThanThemselvesCanBeAnagrams() { + assertThat(new Anagram("LISTEN").match(List.of("LISTEN", "Silent"))) + .containsExactlyInAnyOrderElementsOf(List.of("Silent")); } @Disabled("Remove to run test") @Test @DisplayName("handles case of greek letters") - public void testHandlesCaseOfGreekLetters() { - Anagram detector = new Anagram("ΑΒΓ"); - - assertThat(detector.match(Arrays.asList("ΒΓΑ", "ΒΓΔ", "γβα", "αβγ"))) - .containsExactlyInAnyOrder("ΒΓΑ", "γβα"); + public void handlesCaseOfGreekLetters() { + assertThat(new Anagram("ΑΒΓ").match(List.of("ΒΓΑ", "ΒΓΔ", "γβα", "αβγ"))) + .containsExactlyInAnyOrderElementsOf(List.of("ΒΓΑ", "γβα")); } @Disabled("Remove to run test") @Test @DisplayName("different characters may have the same bytes") - public void testDifferentCharactersWithSameBytes() { - Anagram detector = new Anagram("a⬂"); - - assertThat(detector.match(Collections.singletonList("€a"))) - .isEmpty(); + public void differentCharactersMayHaveTheSameBytes() { + assertThat(new Anagram("a⬂").match(List.of("€a"))) + .containsExactlyInAnyOrderElementsOf(List.of()); } + } diff --git a/exercises/practice/armstrong-numbers/src/test/java/ArmstrongNumbersTest.java b/exercises/practice/armstrong-numbers/src/test/java/ArmstrongNumbersTest.java index 8977970dc..859b12999 100644 --- a/exercises/practice/armstrong-numbers/src/test/java/ArmstrongNumbersTest.java +++ b/exercises/practice/armstrong-numbers/src/test/java/ArmstrongNumbersTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,81 +6,74 @@ public class ArmstrongNumbersTest { - private ArmstrongNumbers armstrongNumbers; - - @BeforeEach - public void setup() { - armstrongNumbers = new ArmstrongNumbers(); - } - @Test @DisplayName("Zero is an Armstrong number") - public void zeroIsArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(0)) + public void zeroIsAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(0)) .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("Single-digit numbers are Armstrong numbers") - public void singleDigitsAreArmstrongNumbers() { - assertThat(armstrongNumbers.isArmstrongNumber(5)) + public void singleDigitNumbersAreArmstrongNumbers() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(5)) .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("There are no two-digit Armstrong numbers") - public void noTwoDigitArmstrongNumbers() { - assertThat(armstrongNumbers.isArmstrongNumber(10)) + public void thereAreNoTwoDigitArmstrongNumbers() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(10)) .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("Three-digit number that is an Armstrong number") - public void threeDigitNumberIsArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(153)) + public void threeDigitNumberThatIsAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(153)) .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("Three-digit number that is not an Armstrong number") - public void threeDigitNumberIsNotArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(100)) + public void threeDigitNumberThatIsNotAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(100)) .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("Four-digit number that is an Armstrong number") - public void fourDigitNumberIsArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(9474)) + public void fourDigitNumberThatIsAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(9474)) .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("Four-digit number that is not an Armstrong number") - public void fourDigitNumberIsNotArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(9475)) + public void fourDigitNumberThatIsNotAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(9475)) .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("Seven-digit number that is an Armstrong number") - public void sevenDigitNumberIsArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(9926315)) + public void sevenDigitNumberThatIsAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(9926315)) .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("Seven-digit number that is not an Armstrong number") - public void sevenDigitNumberIsNotArmstrongNumber() { - assertThat(armstrongNumbers.isArmstrongNumber(9926314)) + public void sevenDigitNumberThatIsNotAnArmstrongNumber() { + assertThat(new ArmstrongNumbers().isArmstrongNumber(9926314)) .isFalse(); } diff --git a/exercises/practice/atbash-cipher/src/test/java/AtbashTest.java b/exercises/practice/atbash-cipher/src/test/java/AtbashTest.java index c914f8b28..52ce43c69 100644 --- a/exercises/practice/atbash-cipher/src/test/java/AtbashTest.java +++ b/exercises/practice/atbash-cipher/src/test/java/AtbashTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,114 +6,115 @@ public class AtbashTest { - private Atbash atbash; - - @BeforeEach - public void setup() { - atbash = new Atbash(); - } - @Test - @DisplayName("encode yes") - public void testEncodeYes() { - assertThat(atbash.encode("yes")).isEqualTo("bvh"); + @DisplayName("encode -> encode yes") + public void encodeEncodeYes() { + assertThat(new Atbash().encode("yes")) + .isEqualTo("bvh"); } @Disabled("Remove to run test") @Test - @DisplayName("encode no") - public void testEncodeNo() { - assertThat(atbash.encode("no")).isEqualTo("ml"); + @DisplayName("encode -> encode no") + public void encodeEncodeNo() { + assertThat(new Atbash().encode("no")) + .isEqualTo("ml"); } @Disabled("Remove to run test") @Test - @DisplayName("encode OMG") - public void testEncodeOmgInCapital() { - assertThat(atbash.encode("OMG")).isEqualTo("lnt"); + @DisplayName("encode -> encode OMG") + public void encodeEncodeOmg() { + assertThat(new Atbash().encode("OMG")) + .isEqualTo("lnt"); } @Disabled("Remove to run test") @Test - @DisplayName("encode spaces") - public void testEncodeOmgWithSpaces() { - assertThat(atbash.encode("O M G")).isEqualTo("lnt"); + @DisplayName("encode -> encode spaces") + public void encodeEncodeSpaces() { + assertThat(new Atbash().encode("O M G")) + .isEqualTo("lnt"); } @Disabled("Remove to run test") @Test - @DisplayName("encode mindblowingly") - public void testEncodeMindBlowingly() { - assertThat(atbash.encode("mindblowingly")).isEqualTo("nrmwy oldrm tob"); + @DisplayName("encode -> encode mindblowingly") + public void encodeEncodeMindblowingly() { + assertThat(new Atbash().encode("mindblowingly")) + .isEqualTo("nrmwy oldrm tob"); } @Disabled("Remove to run test") @Test - @DisplayName("encode numbers") - public void testEncodeNumbers() { - assertThat(atbash.encode("Testing,1 2 3, testing.")) + @DisplayName("encode -> encode numbers") + public void encodeEncodeNumbers() { + assertThat(new Atbash().encode("Testing,1 2 3, testing.")) .isEqualTo("gvhgr mt123 gvhgr mt"); } @Disabled("Remove to run test") @Test - @DisplayName("encode deep thought") - public void testEncodeDeepThought() { - assertThat(atbash.encode("Truth is fiction.")) + @DisplayName("encode -> encode deep thought") + public void encodeEncodeDeepThought() { + assertThat(new Atbash().encode("Truth is fiction.")) .isEqualTo("gifgs rhurx grlm"); } @Disabled("Remove to run test") @Test - @DisplayName("encode all the letters") - public void testEncodeAllTheLetters() { - assertThat(atbash.encode("The quick brown fox jumps over the lazy dog.")) + @DisplayName("encode -> encode all the letters") + public void encodeEncodeAllTheLetters() { + assertThat(new Atbash().encode("The quick brown fox jumps over the lazy dog.")) .isEqualTo("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"); } @Disabled("Remove to run test") @Test - @DisplayName("decode exercism") - public void testDecodeExercism() { - assertThat(atbash.decode("vcvix rhn")).isEqualTo("exercism"); + @DisplayName("decode -> decode exercism") + public void decodeDecodeExercism() { + assertThat(new Atbash().decode("vcvix rhn")) + .isEqualTo("exercism"); } @Disabled("Remove to run test") @Test - @DisplayName("decode a sentence") - public void testDecodeASentence() { - assertThat(atbash.decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")) + @DisplayName("decode -> decode a sentence") + public void decodeDecodeASentence() { + assertThat(new Atbash().decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")) .isEqualTo("anobstacleisoftenasteppingstone"); } @Disabled("Remove to run test") @Test - @DisplayName("decode numbers") - public void testDecodeNumbers() { - assertThat(atbash.decode("gvhgr mt123 gvhgr mt")) + @DisplayName("decode -> decode numbers") + public void decodeDecodeNumbers() { + assertThat(new Atbash().decode("gvhgr mt123 gvhgr mt")) .isEqualTo("testing123testing"); } @Disabled("Remove to run test") @Test - @DisplayName("decode all the letters") - public void testDecodeAllTheLetters() { - assertThat(atbash.decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")) + @DisplayName("decode -> decode all the letters") + public void decodeDecodeAllTheLetters() { + assertThat(new Atbash().decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")) .isEqualTo("thequickbrownfoxjumpsoverthelazydog"); } @Disabled("Remove to run test") @Test - @DisplayName("decode with too many spaces") - public void testDecodeWithTooManySpaces() { - assertThat(atbash.decode("vc vix r hn")).isEqualTo("exercism"); + @DisplayName("decode -> decode with too many spaces") + public void decodeDecodeWithTooManySpaces() { + assertThat(new Atbash().decode("vc vix r hn")) + .isEqualTo("exercism"); } @Disabled("Remove to run test") @Test - @DisplayName("decode with no spaces") - public void testDecodeWithNoSpaces() { - assertThat(atbash.decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv")) + @DisplayName("decode -> decode with no spaces") + public void decodeDecodeWithNoSpaces() { + assertThat(new Atbash().decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv")) .isEqualTo("anobstacleisoftenasteppingstone"); } + } diff --git a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java index 0726301dc..70303f36d 100644 --- a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java +++ b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java @@ -1,176 +1,208 @@ -import java.time.LocalDate; -import java.util.List; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static java.time.Month.APRIL; -import static java.time.Month.AUGUST; -import static java.time.Month.DECEMBER; -import static java.time.Month.FEBRUARY; -import static java.time.Month.JANUARY; -import static java.time.Month.JULY; -import static java.time.Month.MAY; -import static java.time.Month.NOVEMBER; -import static java.time.Month.OCTOBER; +import java.time.LocalDate; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.Offset.offset; +import static org.assertj.core.api.Assertions.offset; public class BafflingBirthdaysTest { + private BafflingBirthdays birthdays = new BafflingBirthdays(); @Test - @DisplayName("one birthdate") - public void oneBirthdateTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(2000, JANUARY, 1) - ))).isFalse(); + @DisplayName("shared birthday -> one birthdate") + public void sharedBirthdayOneBirthdate() { + + List birthdates = List.of(LocalDate.parse("2000-01-01")); + + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("two birthdates with same year, month, and day") - public void twoBirthdatesWithSameYearMonthAndDayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(2000, JANUARY, 1), - LocalDate.of(2000, JANUARY, 1) - ))).isTrue(); + @DisplayName("shared birthday -> two birthdates with same year, month, and day") + public void sharedBirthdayTwoBirthdatesWithSameYearMonthAndDay() { + + List birthdates = List.of(LocalDate.parse("2000-01-01"), LocalDate.parse("2000-01-01")); + + assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("two birthdates with same year and month, but different day") - public void twoBirthdatesWithSameYearAndMonthButDifferentDayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(2012, MAY, 9), - LocalDate.of(2012, MAY, 17) - ))).isFalse(); + @DisplayName("shared birthday -> two birthdates with same year and month, but different day") + public void sharedBirthdayTwoBirthdatesWithSameYearAndMonthButDifferentDay() { + + List birthdates = List.of(LocalDate.parse("2012-05-09"), LocalDate.parse("2012-05-17")); + + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("two birthdates with same month and day, but different year") - public void twoBirthdatesWithSameMonthAndDayButDifferentYearTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(1999, OCTOBER, 23), - LocalDate.of(1988, OCTOBER, 23) - ))).isTrue(); + @DisplayName("shared birthday -> two birthdates with same month and day, but different year") + public void sharedBirthdayTwoBirthdatesWithSameMonthAndDayButDifferentYear() { + + List birthdates = List.of(LocalDate.parse("1999-10-23"), LocalDate.parse("1988-10-23")); + + assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("two birthdates with same year, but different month and day") - public void twoBirthdatesWithSameYearButDifferentMonthAndDayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(2007, DECEMBER, 19), - LocalDate.of(2007, APRIL, 27) - ))).isFalse(); + @DisplayName("shared birthday -> two birthdates with same year, but different month and day") + public void sharedBirthdayTwoBirthdatesWithSameYearButDifferentMonthAndDay() { + + List birthdates = List.of(LocalDate.parse("2007-12-19"), LocalDate.parse("2007-04-27")); + + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("two birthdates with different year, month, and day") - public void twoBirthdatesWithDifferentYearMonthAndDayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(1997, AUGUST, 4), - LocalDate.of(1963, NOVEMBER, 23) - ))).isFalse(); + @DisplayName("shared birthday -> two birthdates with different year, month, and day") + public void sharedBirthdayTwoBirthdatesWithDifferentYearMonthAndDay() { + + List birthdates = List.of(LocalDate.parse("1997-08-04"), LocalDate.parse("1963-11-23")); + + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple birthdates without shared birthday") - public void multipleBirthdatesWithoutSharedBirthdayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(1966, AUGUST, 29), - LocalDate.of(1977, FEBRUARY, 12), - LocalDate.of(2001, DECEMBER, 25), - LocalDate.of(1980, NOVEMBER, 10) - ))).isFalse(); + @DisplayName("shared birthday -> multiple birthdates without shared birthday") + public void sharedBirthdayMultipleBirthdatesWithoutSharedBirthday() { + + List birthdates = List.of( + LocalDate.parse("1966-07-29"), + LocalDate.parse("1977-02-12"), + LocalDate.parse("2001-12-25"), + LocalDate.parse("1980-11-10") + ); + + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple birthdates with one shared birthday") - public void multipleBirthdatesWithOneSharedBirthdayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(1966, AUGUST, 29), - LocalDate.of(1977, FEBRUARY, 12), - LocalDate.of(2001, AUGUST, 29), - LocalDate.of(1980, NOVEMBER, 10) - ))).isTrue(); + @DisplayName("shared birthday -> multiple birthdates with one shared birthday") + public void sharedBirthdayMultipleBirthdatesWithOneSharedBirthday() { + + List birthdates = List.of( + LocalDate.parse("1966-07-29"), + LocalDate.parse("1977-02-12"), + LocalDate.parse("2001-07-29"), + LocalDate.parse("1980-11-10") + ); + + assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple birthdates with more than one shared birthday") - public void multipleBirthdatesWithMoreThanOneSharedBirthdayTest() { - assertThat(birthdays.sharedBirthday(List.of( - LocalDate.of(1966, JULY, 29), - LocalDate.of(1977, FEBRUARY, 12), - LocalDate.of(2001, DECEMBER, 25), - LocalDate.of(1980, JULY, 29), - LocalDate.of(2019, FEBRUARY, 12) - ))).isTrue(); + @DisplayName("shared birthday -> multiple birthdates with more than one shared birthday") + public void sharedBirthdayMultipleBirthdatesWithMoreThanOneSharedBirthday() { + + List birthdates = List.of( + LocalDate.parse("1966-07-29"), + LocalDate.parse("1977-02-12"), + LocalDate.parse("2001-12-25"), + LocalDate.parse("1980-07-29"), + LocalDate.parse("2019-02-12") + ); + + assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("generate requested number of birthdates") - public void generateRequestedNumberOfBirthdatesTest() { + @DisplayName("random birthdates -> generate requested number of birthdates") + public void randomBirthdatesGenerateRequestedNumberOfBirthdates() { + int groupSize = 50; assertThat(birthdays.randomBirthdates(groupSize).size()).isEqualTo(groupSize); + } @Disabled("Remove to run test") @Test - @DisplayName("years are not leap years") - public void yearsAreNotLeapYearsTest() { + @DisplayName("random birthdates -> years are not leap years") + public void randomBirthdatesYearsAreNotLeapYears() { + assertThat(birthdays.randomBirthdates(100)).noneMatch(LocalDate::isLeapYear); + } @Disabled("Remove to run test") @Test - @DisplayName("months are random") - public void monthsAreRandomTest() { + @DisplayName("random birthdates -> months are random") + public void randomBirthdatesMonthsAreRandom() { + assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getMonth).distinct()) .hasSizeGreaterThanOrEqualTo(7); + } @Disabled("Remove to run test") @Test - @DisplayName("days are random") - public void daysAreRandomTest() { + @DisplayName("random birthdates -> days are random") + public void randomBirthdatesDaysAreRandom() { + assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getDayOfMonth).distinct()) .hasSizeGreaterThanOrEqualTo(11); + } @Disabled("Remove to run test") @Test - @DisplayName("estimated probability of at least one shared birthday case for one person") - public void estimatedProbabilityOfAtLeastOneSharedBirthdayForOnePersonTest() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(1)).isEqualTo(0.0); + @DisplayName("estimated probability of at least one shared birthday -> for one person") + public void estimatedProbabilityOfAtLeastOneSharedBirthdayForOnePerson() { + + assertThat(birthdays.estimatedProbabilityOfSharedBirthday(1)) + .isEqualTo(0.0); + } @Disabled("Remove to run test") @Test - @DisplayName("estimated probability of at least one shared birthday case among ten people") - public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTenPeopleTest() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(10)).isCloseTo(11.694818, offset(1.0)); + @DisplayName("estimated probability of at least one shared birthday -> among ten people") + public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTenPeople() { + + assertThat(birthdays.estimatedProbabilityOfSharedBirthday(10)) + .isCloseTo(11.694818, offset(1.0)); + } @Disabled("Remove to run test") @Test - @DisplayName("estimated probability of at least one shared birthday case among twenty-three people") - public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTwentyThreePeopleTest() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(23)).isCloseTo(50.729723, offset(1.0)); + @DisplayName("estimated probability of at least one shared birthday -> among twenty-three people") + public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTwentyThreePeo() { + + assertThat(birthdays.estimatedProbabilityOfSharedBirthday(23)) + .isCloseTo(50.729723, offset(1.0)); + } @Disabled("Remove to run test") @Test - @DisplayName("estimated probability of at least one shared birthday case among seventy people") - public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongSeventyPeopleTest() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(70)).isCloseTo(99.915958, offset(1.0)); + @DisplayName("estimated probability of at least one shared birthday -> among seventy people") + public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongSeventyPeople() { + + assertThat(birthdays.estimatedProbabilityOfSharedBirthday(70)) + .isCloseTo(99.915958, offset(1.0)); + } + } diff --git a/exercises/practice/bank-account/src/test/java/BankAccountTest.java b/exercises/practice/bank-account/src/test/java/BankAccountTest.java index 8c6d65de7..0e96e8857 100644 --- a/exercises/practice/bank-account/src/test/java/BankAccountTest.java +++ b/exercises/practice/bank-account/src/test/java/BankAccountTest.java @@ -1,231 +1,211 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Random; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; public class BankAccountTest { - private BankAccount bankAccount; - - @BeforeEach - public void setUp() { - bankAccount = new BankAccount(); - } @Test @DisplayName("Newly opened account has zero balance") - public void newlyOpenedAccountHasEmptyBalance() throws BankAccountActionInvalidException { + public void newlyOpenedAccountHasZeroBalance() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); - assertThat(bankAccount.getBalance()).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Single deposit") - public void singleDeposit() throws BankAccountActionInvalidException { + public void singleDeposit() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); - assertThat(bankAccount.getBalance()).isEqualTo(100); } @Disabled("Remove to run test") @Test @DisplayName("Multiple deposits") - public void multipleDeposits() throws BankAccountActionInvalidException { + public void multipleDeposits() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); bankAccount.deposit(50); - assertThat(bankAccount.getBalance()).isEqualTo(150); } @Disabled("Remove to run test") @Test @DisplayName("Withdraw once") - public void withdrawOnce() throws BankAccountActionInvalidException { + public void withdrawOnce() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); bankAccount.withdraw(75); - assertThat(bankAccount.getBalance()).isEqualTo(25); } @Disabled("Remove to run test") @Test @DisplayName("Withdraw twice") - public void withdrawTwice() throws BankAccountActionInvalidException { + public void withdrawTwice() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); bankAccount.withdraw(80); bankAccount.withdraw(20); - assertThat(bankAccount.getBalance()).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Can do multiple operations sequentially") - public void canDoMultipleOperationsSequentially() throws BankAccountActionInvalidException { + public void canDoMultipleOperationsSequentially() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); bankAccount.deposit(110); bankAccount.withdraw(200); bankAccount.deposit(60); bankAccount.withdraw(50); - assertThat(bankAccount.getBalance()).isEqualTo(20); } @Disabled("Remove to run test") @Test @DisplayName("Cannot check balance of closed account") - public void cannotCheckBalanceOfClosedAccount() throws BankAccountActionInvalidException { + public void cannotCheckBalanceOfClosedAccount() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.close(); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(bankAccount::getBalance) - .withMessage("Account closed"); + .isThrownBy(() -> bankAccount.getBalance()); } @Disabled("Remove to run test") @Test @DisplayName("Cannot deposit into closed account") - public void cannotDepositIntoClosedAccount() throws BankAccountActionInvalidException { + public void cannotDepositIntoClosedAccount() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.close(); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.deposit(50)) - .withMessage("Account closed"); + .isThrownBy(() -> bankAccount.deposit(50)); } @Disabled("Remove to run test") @Test @DisplayName("Cannot deposit into unopened account") - public void cannotDepositIntoUnopenedAccount() { + public void cannotDepositIntoUnopenedAccount() throws Exception { + BankAccount bankAccount = new BankAccount(); assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.deposit(50)) - .withMessage("Account closed"); + .isThrownBy(() -> bankAccount.deposit(50)); } @Disabled("Remove to run test") @Test @DisplayName("Cannot withdraw from closed account") - public void cannotWithdrawFromClosedAccount() throws BankAccountActionInvalidException { + public void cannotWithdrawFromClosedAccount() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.close(); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.withdraw(50)) - .withMessage("Account closed"); + .isThrownBy(() -> bankAccount.withdraw(50)); } @Disabled("Remove to run test") @Test @DisplayName("Cannot close an account that was not opened") - public void cannotCloseAnAccountThatWasNotOpened() { + public void cannotCloseAnAccountThatWasNotOpened() throws Exception { + BankAccount bankAccount = new BankAccount(); assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(bankAccount::close) - .withMessage("Account not open"); + .isThrownBy(() -> bankAccount.close()); } @Disabled("Remove to run test") @Test @DisplayName("Cannot open an already opened account") - public void cannotOpenAnAlreadyOpenedAccount() throws BankAccountActionInvalidException { + public void cannotOpenAnAlreadyOpenedAccount() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(bankAccount::open) - .withMessage("Account already open"); + .isThrownBy(() -> bankAccount.open()); } @Disabled("Remove to run test") @Test @DisplayName("Reopened account does not retain balance") - public void reopenedAccountDoesNotRetainBalance() throws BankAccountActionInvalidException { + public void reopenedAccountDoesNotRetainBalance() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(50); bankAccount.close(); bankAccount.open(); - assertThat(bankAccount.getBalance()).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Cannot withdraw more than deposited") - public void cannotWithdrawMoreThanDeposited() throws BankAccountActionInvalidException { + public void cannotWithdrawMoreThanDeposited() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(25); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.withdraw(50)) - .withMessage("Cannot withdraw more money than is currently in the account"); + .isThrownBy(() -> bankAccount.withdraw(50)); } @Disabled("Remove to run test") @Test @DisplayName("Cannot withdraw negative") - public void cannotWithdrawNegativeAmount() throws BankAccountActionInvalidException { + public void cannotWithdrawNegative() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); bankAccount.deposit(100); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.withdraw(-50)) - .withMessage("Cannot deposit or withdraw negative amount"); + .isThrownBy(() -> bankAccount.withdraw(-50)); } @Disabled("Remove to run test") @Test @DisplayName("Cannot deposit negative") - public void cannotDepositNegativeAmount() throws BankAccountActionInvalidException { + public void cannotDepositNegative() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); - assertThatExceptionOfType(BankAccountActionInvalidException.class) - .isThrownBy(() -> bankAccount.deposit(-50)) - .withMessage("Cannot deposit or withdraw negative amount"); + .isThrownBy(() -> bankAccount.deposit(-50)); } @Disabled("Remove to run test") @Test @DisplayName("Can handle concurrent transactions") - public void canHandleConcurrentTransactions() throws BankAccountActionInvalidException, InterruptedException { + public void canHandleConcurrentTransactions() throws Exception { + BankAccount bankAccount = new BankAccount(); bankAccount.open(); - bankAccount.deposit(1000); - - for (int i = 0; i < 10; i++) { - adjustBalanceConcurrently(); - assertThat(bankAccount.getBalance()).isEqualTo(1000); - } - } - - private void adjustBalanceConcurrently() throws InterruptedException { Random random = new Random(); - Thread[] threads = new Thread[1000]; - for (int i = 0; i < 1000; i++) { - threads[i] = new Thread(() -> { + for (int idx = 0; idx < 1000; idx++) { + threads[idx] = new Thread(() -> { try { - bankAccount.deposit(5); + bankAccount.deposit(1); Thread.sleep(random.nextInt(10)); - bankAccount.withdraw(5); + bankAccount.withdraw(1); } catch (BankAccountActionInvalidException e) { fail("Exception should not be thrown: " + e.getMessage()); } catch (InterruptedException ignored) { } }); - threads[i].start(); + threads[idx].start(); } - for (Thread thread : threads) { thread.join(); } + assertThat(bankAccount.getBalance()).isEqualTo(0); } + } diff --git a/exercises/practice/binary-search-tree/src/test/java/BinarySearchTreeTest.java b/exercises/practice/binary-search-tree/src/test/java/BinarySearchTreeTest.java index f6d8f1478..515518205 100644 --- a/exercises/practice/binary-search-tree/src/test/java/BinarySearchTreeTest.java +++ b/exercises/practice/binary-search-tree/src/test/java/BinarySearchTreeTest.java @@ -1,167 +1,131 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; public class BinarySearchTreeTest { @Test @DisplayName("data is retained") public void dataIsRetained() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - - int expected = 4; - binarySearchTree.insert(expected); - - BinarySearchTree.Node root = binarySearchTree.getRoot(); - + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + binarySearchTree.insert("4"); + BinarySearchTree.Node root = binarySearchTree.getRoot(); assertThat(root).isNotNull(); - assertThat(root.getData()).isEqualTo(expected); + assertThat(root.getData()).isEqualTo("4"); } - @Disabled("Remove to run test") @Test - @DisplayName("insert data at proper node") - public void insertsLess() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - - char expectedRoot = '4'; - char expectedLeft = '2'; - - binarySearchTree.insert(expectedRoot); - binarySearchTree.insert(expectedLeft); - - BinarySearchTree.Node root = binarySearchTree.getRoot(); - BinarySearchTree.Node left = root.getLeft(); - + @DisplayName("insert data at proper node -> smaller number at left node") + public void insertDataAtProperNodeSmallerNumberAtLeftNode() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + binarySearchTree.insert("4"); + binarySearchTree.insert("2"); + BinarySearchTree.Node root = binarySearchTree.getRoot(); assertThat(root).isNotNull(); + assertThat(root.getData()).isEqualTo("4"); + BinarySearchTree.Node left = root.getLeft(); assertThat(left).isNotNull(); - - assertThat(root.getData()).isEqualTo(expectedRoot); - assertThat(left.getData()).isEqualTo(expectedLeft); + assertThat(left.getData()).isEqualTo("2"); } @Disabled("Remove to run test") @Test - @DisplayName("same number at left node") - public void insertsSame() { + @DisplayName("insert data at proper node -> same number at left node") + public void insertDataAtProperNodeSameNumberAtLeftNode() { BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - String expectedRoot = "4"; - String expectedLeft = "4"; - - binarySearchTree.insert(expectedRoot); - binarySearchTree.insert(expectedLeft); - + binarySearchTree.insert("4"); + binarySearchTree.insert("4"); BinarySearchTree.Node root = binarySearchTree.getRoot(); - BinarySearchTree.Node left = root.getLeft(); - assertThat(root).isNotNull(); + assertThat(root.getData()).isEqualTo("4"); + BinarySearchTree.Node left = root.getLeft(); assertThat(left).isNotNull(); - - assertThat(root.getData()).isEqualTo(expectedRoot); - assertThat(left.getData()).isEqualTo(expectedLeft); + assertThat(left.getData()).isEqualTo("4"); } @Disabled("Remove to run test") @Test - @DisplayName("greater number at right node") - public void insertsRight() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - int expectedRoot = 4; - int expectedRight = 5; - - binarySearchTree.insert(expectedRoot); - binarySearchTree.insert(expectedRight); - - BinarySearchTree.Node root = binarySearchTree.getRoot(); - BinarySearchTree.Node right = root.getRight(); - + @DisplayName("insert data at proper node -> greater number at right node") + public void insertDataAtProperNodeGreaterNumberAtRightNode() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + binarySearchTree.insert("4"); + binarySearchTree.insert("5"); + BinarySearchTree.Node root = binarySearchTree.getRoot(); assertThat(root).isNotNull(); + assertThat(root.getData()).isEqualTo("4"); + BinarySearchTree.Node right = root.getRight(); assertThat(right).isNotNull(); - - assertThat(root.getData()).isEqualTo(expectedRoot); - assertThat(right.getData()).isEqualTo(expectedRight); + assertThat(right.getData()).isEqualTo("5"); } @Disabled("Remove to run test") @Test @DisplayName("can create complex tree") - public void createsComplexTree() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = List.of('4', '2', '6', '1', '3', '5', '7'); - - List treeData = List.of('4', '2', '6', '1', '3', '5', '7'); - treeData.forEach(binarySearchTree::insert); - - assertThat(binarySearchTree.getAsLevelOrderList()).isEqualTo(expected); + public void canCreateComplexTree() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + binarySearchTree.insert("4"); + binarySearchTree.insert("2"); + binarySearchTree.insert("6"); + binarySearchTree.insert("1"); + binarySearchTree.insert("3"); + binarySearchTree.insert("5"); + binarySearchTree.insert("7"); + assertThat(binarySearchTree.getAsLevelOrderList()).isEqualTo(List.of("4", "2", "6", "1", "3", "5", "7")); } @Disabled("Remove to run test") @Test - @DisplayName("can sort single number") - public void sortsSingleElement() { + @DisplayName("can sort data -> can sort single number") + public void canSortDataCanSortSingleNumber() { BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = Collections.singletonList("2"); - - binarySearchTree.insert("2"); - - assertThat(binarySearchTree.getAsSortedList()).isEqualTo(expected); + List treeData = List.of("2"); + treeData.forEach(binarySearchTree::insert); + assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of("2")); } @Disabled("Remove to run test") @Test - @DisplayName("can sort if second number is smaller than first") - public void sortsCollectionOfTwoIfSecondInsertedIsSmallerThanFirst() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = List.of(1, 2); - - binarySearchTree.insert(2); - binarySearchTree.insert(1); - - assertThat(binarySearchTree.getAsSortedList()).isEqualTo(expected); + @DisplayName("can sort data -> can sort if second number is smaller than first") + public void canSortDataCanSortIfSecondNumberIsSmallerThanFirst() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + List treeData = List.of("2", "1"); + treeData.forEach(binarySearchTree::insert); + assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of("1", "2")); } @Disabled("Remove to run test") @Test - @DisplayName("can sort if second number is same as first") - public void sortsCollectionOfTwoIfSecondNumberisSameAsFirst() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = List.of('2', '2'); - - binarySearchTree.insert('2'); - binarySearchTree.insert('2'); - - assertThat(binarySearchTree.getAsSortedList()).isEqualTo(expected); + @DisplayName("can sort data -> can sort if second number is same as first") + public void canSortDataCanSortIfSecondNumberIsSameAsFirst() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + List treeData = List.of("2", "2"); + treeData.forEach(binarySearchTree::insert); + assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of("2", "2")); } @Disabled("Remove to run test") @Test - @DisplayName("can sort if second number is greater than first") - public void sortsCollectionOfTwoIfSecondInsertedIsBiggerThanFirst() { - BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = List.of('2', '3'); - - binarySearchTree.insert('2'); - binarySearchTree.insert('3'); - - assertThat(binarySearchTree.getAsSortedList()).isEqualTo(expected); + @DisplayName("can sort data -> can sort if second number is greater than first") + public void canSortDataCanSortIfSecondNumberIsGreaterThanFirst() { + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + List treeData = List.of("2", "3"); + treeData.forEach(binarySearchTree::insert); + assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of("2", "3")); } @Disabled("Remove to run test") @Test - @DisplayName("can sort complex tree") - public void iteratesOverComplexTree() { + @DisplayName("can sort data -> can sort complex tree") + public void canSortDataCanSortComplexTree() { BinarySearchTree binarySearchTree = new BinarySearchTree<>(); - List expected = List.of("1", "2", "3", "5", "6", "7"); - List treeData = List.of("2", "1", "3", "6", "7", "5"); treeData.forEach(binarySearchTree::insert); - - assertThat(binarySearchTree.getAsSortedList()).isEqualTo(expected); + assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of("1", "2", "3", "5", "6", "7")); } + } diff --git a/exercises/practice/binary-search/src/test/java/BinarySearchTest.java b/exercises/practice/binary-search/src/test/java/BinarySearchTest.java index 4846489c9..75ddd26f3 100644 --- a/exercises/practice/binary-search/src/test/java/BinarySearchTest.java +++ b/exercises/practice/binary-search/src/test/java/BinarySearchTest.java @@ -1,143 +1,164 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class BinarySearchTest { @Test @DisplayName("finds a value in an array with one element") public void findsAValueInAnArrayWithOneElement() throws ValueNotFoundException { - List listOfUnitLength = Collections.singletonList(6); - BinarySearch search = new BinarySearch(listOfUnitLength); + assertThat(new BinarySearch(List.of(6)) + .indexOf(6)) + .isEqualTo(0); - assertThat(search.indexOf(6)).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("finds a value in the middle of an array") public void findsAValueInTheMiddleOfAnArray() throws ValueNotFoundException { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - BinarySearch search = new BinarySearch(sortedList); + assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(6)) + .isEqualTo(3); - assertThat(search.indexOf(6)).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("finds a value at the beginning of an array") public void findsAValueAtTheBeginningOfAnArray() throws ValueNotFoundException { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - BinarySearch search = new BinarySearch(sortedList); + assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(1)) + .isEqualTo(0); - assertThat(search.indexOf(1)).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("finds a value at the end of an array") public void findsAValueAtTheEndOfAnArray() throws ValueNotFoundException { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - BinarySearch search = new BinarySearch(sortedList); + assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(11)) + .isEqualTo(6); - assertThat(search.indexOf(11)).isEqualTo(6); } @Disabled("Remove to run test") @Test @DisplayName("finds a value in an array of odd length") public void findsAValueInAnArrayOfOddLength() throws ValueNotFoundException { - List sortedListOfOddLength = List.of(1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634); - BinarySearch search = new BinarySearch(sortedListOfOddLength); + assertThat(new BinarySearch(List.of( + 1, + 3, + 5, + 8, + 13, + 21, + 34, + 55, + 89, + 144, + 233, + 377, + 634 + )) + .indexOf(144)) + .isEqualTo(9); - assertThat(search.indexOf(144)).isEqualTo(9); } @Disabled("Remove to run test") @Test @DisplayName("finds a value in an array of even length") public void findsAValueInAnArrayOfEvenLength() throws ValueNotFoundException { - List sortedListOfEvenLength = List.of(1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377); - BinarySearch search = new BinarySearch(sortedListOfEvenLength); + assertThat(new BinarySearch(List.of( + 1, + 3, + 5, + 8, + 13, + 21, + 34, + 55, + 89, + 144, + 233, + 377 + )) + .indexOf(21)) + .isEqualTo(5); - assertThat(search.indexOf(21)).isEqualTo(5); } @Disabled("Remove to run test") @Test @DisplayName("identifies that a value is not included in the array") - public void identifiesThatAValueIsNotFoundInTheArray() { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - - BinarySearch search = new BinarySearch(sortedList); + public void identifiesThatAValueIsNotIncludedInTheArray() throws ValueNotFoundException { assertThatExceptionOfType(ValueNotFoundException.class) - .isThrownBy(() -> search.indexOf(7)) - .withMessage("Value not in array"); + .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(7)) + .withMessage("Value not in array"); + } @Disabled("Remove to run test") @Test @DisplayName("a value smaller than the array's smallest value is not found") - public void aValueSmallerThanTheArraysSmallestValueIsNotFound() { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - - BinarySearch search = new BinarySearch(sortedList); + public void aValueSmallerThanTheArraySSmallestValueIsNotFound() throws ValueNotFoundException { assertThatExceptionOfType(ValueNotFoundException.class) - .isThrownBy(() -> search.indexOf(0)) - .withMessage("Value not in array"); + .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(0)) + .withMessage("Value not in array"); + } @Disabled("Remove to run test") @Test @DisplayName("a value larger than the array's largest value is not found") - public void aValueLargerThanTheArraysLargestValueIsNotFound() throws ValueNotFoundException { - List sortedList = List.of(1, 3, 4, 6, 8, 9, 11); - - BinarySearch search = new BinarySearch(sortedList); + public void aValueLargerThanTheArraySLargestValueIsNotFound() throws ValueNotFoundException { assertThatExceptionOfType(ValueNotFoundException.class) - .isThrownBy(() -> search.indexOf(13)) - .withMessage("Value not in array"); + .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) + .indexOf(13)) + .withMessage("Value not in array"); + } @Disabled("Remove to run test") @Test @DisplayName("nothing is found in an empty array") public void nothingIsFoundInAnEmptyArray() throws ValueNotFoundException { - List emptyList = Collections.emptyList(); - - BinarySearch search = new BinarySearch(emptyList); assertThatExceptionOfType(ValueNotFoundException.class) - .isThrownBy(() -> search.indexOf(1)) - .withMessage("Value not in array"); + .isThrownBy(() -> new BinarySearch(List.of()) + .indexOf(1)) + .withMessage("Value not in array"); + } @Disabled("Remove to run test") @Test @DisplayName("nothing is found when the left and right bounds cross") - public void nothingIsFoundWhenTheLeftAndRightBoundCross() throws ValueNotFoundException { - List sortedList = List.of(1, 2); - - BinarySearch search = new BinarySearch(sortedList); + public void nothingIsFoundWhenTheLeftAndRightBoundsCross() throws ValueNotFoundException { assertThatExceptionOfType(ValueNotFoundException.class) - .isThrownBy(() -> search.indexOf(0)) - .withMessage("Value not in array"); + .isThrownBy(() -> new BinarySearch(List.of(1, 2)) + .indexOf(0)) + .withMessage("Value not in array"); + } } diff --git a/exercises/practice/bob/src/test/java/BobTest.java b/exercises/practice/bob/src/test/java/BobTest.java index 3806670ab..7bb30d524 100644 --- a/exercises/practice/bob/src/test/java/BobTest.java +++ b/exercises/practice/bob/src/test/java/BobTest.java @@ -1,23 +1,15 @@ -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; - public class BobTest { - private Bob bob; - - @BeforeEach - public void setUp() { - bob = new Bob(); - } @Test @DisplayName("stating something") - public void saySomething() { - assertThat(bob.hey("Tom-ay-to, tom-aaaah-to.")) + public void statingSomething() { + assertThat(new Bob().hey("Tom-ay-to, tom-aaaah-to.")) .isEqualTo("Whatever."); } @@ -25,7 +17,7 @@ public void saySomething() { @Test @DisplayName("shouting") public void shouting() { - assertThat(bob.hey("WATCH OUT!")) + assertThat(new Bob().hey("WATCH OUT!")) .isEqualTo("Whoa, chill out!"); } @@ -33,15 +25,7 @@ public void shouting() { @Test @DisplayName("shouting gibberish") public void shoutingGibberish() { - assertThat(bob.hey("FCECDFCAAB")) - .isEqualTo("Whoa, chill out!"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("shouting a statement containing a question mark") - public void shoutingAStatementContainingQuestionMark() { - assertThat(bob.hey("DO LIONS EAT PEOPLE? AHHHHH.")) + assertThat(new Bob().hey("FCECDFCAAB")) .isEqualTo("Whoa, chill out!"); } @@ -49,7 +33,7 @@ public void shoutingAStatementContainingQuestionMark() { @Test @DisplayName("asking a question") public void askingAQuestion() { - assertThat(bob.hey("Does this cryogenic chamber make me look fat?")) + assertThat(new Bob().hey("Does this cryogenic chamber make me look fat?")) .isEqualTo("Sure."); } @@ -57,7 +41,7 @@ public void askingAQuestion() { @Test @DisplayName("asking a numeric question") public void askingANumericQuestion() { - assertThat(bob.hey("You are, what, like 15?")) + assertThat(new Bob().hey("You are, what, like 15?")) .isEqualTo("Sure."); } @@ -65,7 +49,7 @@ public void askingANumericQuestion() { @Test @DisplayName("asking gibberish") public void askingGibberish() { - assertThat(bob.hey("fffbbcbeab?")) + assertThat(new Bob().hey("fffbbcbeab?")) .isEqualTo("Sure."); } @@ -73,7 +57,7 @@ public void askingGibberish() { @Test @DisplayName("talking forcefully") public void talkingForcefully() { - assertThat(bob.hey("Hi there!")) + assertThat(new Bob().hey("Hi there!")) .isEqualTo("Whatever."); } @@ -81,15 +65,15 @@ public void talkingForcefully() { @Test @DisplayName("using acronyms in regular speech") public void usingAcronymsInRegularSpeech() { - assertThat(bob.hey("It's OK if you don't want to go work for NASA.")) + assertThat(new Bob().hey("It's OK if you don't want to go work for NASA.")) .isEqualTo("Whatever."); } @Disabled("Remove to run test") @Test @DisplayName("forceful question") - public void forcefulQuestions() { - assertThat(bob.hey("WHAT'S GOING ON?")) + public void forcefulQuestion() { + assertThat(new Bob().hey("WHAT'S GOING ON?")) .isEqualTo("Calm down, I know what I'm doing!"); } @@ -97,23 +81,23 @@ public void forcefulQuestions() { @Test @DisplayName("shouting numbers") public void shoutingNumbers() { - assertThat(bob.hey("1, 2, 3 GO!")) + assertThat(new Bob().hey("1, 2, 3 GO!")) .isEqualTo("Whoa, chill out!"); } @Disabled("Remove to run test") @Test @DisplayName("no letters") - public void onlyNumbers() { - assertThat(bob.hey("1, 2, 3")) + public void noLetters() { + assertThat(new Bob().hey("1, 2, 3")) .isEqualTo("Whatever."); } @Disabled("Remove to run test") @Test @DisplayName("question with no letters") - public void questionWithOnlyNumbers() { - assertThat(bob.hey("4?")) + public void questionWithNoLetters() { + assertThat(new Bob().hey("4?")) .isEqualTo("Sure."); } @@ -121,7 +105,7 @@ public void questionWithOnlyNumbers() { @Test @DisplayName("shouting with special characters") public void shoutingWithSpecialCharacters() { - assertThat(bob.hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")) + assertThat(new Bob().hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")) .isEqualTo("Whoa, chill out!"); } @@ -129,7 +113,7 @@ public void shoutingWithSpecialCharacters() { @Test @DisplayName("shouting with no exclamation mark") public void shoutingWithNoExclamationMark() { - assertThat(bob.hey("I HATE THE DENTIST")) + assertThat(new Bob().hey("I HATE THE DENTIST")) .isEqualTo("Whoa, chill out!"); } @@ -137,7 +121,7 @@ public void shoutingWithNoExclamationMark() { @Test @DisplayName("statement containing question mark") public void statementContainingQuestionMark() { - assertThat(bob.hey("Ending with ? means a question.")) + assertThat(new Bob().hey("Ending with ? means a question.")) .isEqualTo("Whatever."); } @@ -145,7 +129,7 @@ public void statementContainingQuestionMark() { @Test @DisplayName("non-letters with question") public void nonLettersWithQuestion() { - assertThat(bob.hey(":) ?")) + assertThat(new Bob().hey(":) ?")) .isEqualTo("Sure."); } @@ -153,7 +137,7 @@ public void nonLettersWithQuestion() { @Test @DisplayName("prattling on") public void prattlingOn() { - assertThat(bob.hey("Wait! Hang on. Are you going to be OK?")) + assertThat(new Bob().hey("Wait! Hang on. Are you going to be OK?")) .isEqualTo("Sure."); } @@ -161,7 +145,7 @@ public void prattlingOn() { @Test @DisplayName("silence") public void silence() { - assertThat(bob.hey("")) + assertThat(new Bob().hey("")) .isEqualTo("Fine. Be that way!"); } @@ -169,7 +153,7 @@ public void silence() { @Test @DisplayName("prolonged silence") public void prolongedSilence() { - assertThat(bob.hey(" ")) + assertThat(new Bob().hey(" ")) .isEqualTo("Fine. Be that way!"); } @@ -177,7 +161,7 @@ public void prolongedSilence() { @Test @DisplayName("alternate silence") public void alternateSilence() { - assertThat(bob.hey("\t\t\t\t\t\t\t\t\t\t")) + assertThat(new Bob().hey("\t\t\t\t\t\t\t\t\t\t")) .isEqualTo("Fine. Be that way!"); } @@ -185,40 +169,32 @@ public void alternateSilence() { @Test @DisplayName("starting with whitespace") public void startingWithWhitespace() { - assertThat(bob.hey(" hmmmmmmm...")) + assertThat(new Bob().hey(" hmmmmmmm...")) .isEqualTo("Whatever."); } @Disabled("Remove to run test") @Test @DisplayName("ending with whitespace") - public void endingWithWhiteSpace() { - assertThat(bob.hey("Okay if like my spacebar quite a bit? ")) + public void endingWithWhitespace() { + assertThat(new Bob().hey("Okay if like my spacebar quite a bit? ")) .isEqualTo("Sure."); } @Disabled("Remove to run test") @Test @DisplayName("other whitespace") - public void otherWhiteSpace() { - assertThat(bob.hey("\n\r \t")) + public void otherWhitespace() { + assertThat(new Bob().hey("\n\r \t")) .isEqualTo("Fine. Be that way!"); } @Disabled("Remove to run test") @Test @DisplayName("non-question ending with whitespace") - public void nonQuestionEndingWithWhiteSpace() { - assertThat(bob.hey("This is a statement ending with whitespace ")) + public void nonQuestionEndingWithWhitespace() { + assertThat(new Bob().hey("This is a statement ending with whitespace ")) .isEqualTo("Whatever."); } - @Disabled("Remove to run test") - @Test - @DisplayName("multiple line question") - public void multipleLineQuestion() { - assertThat(bob.hey("\nDoes this cryogenic chamber make\n me look fat?")) - .isEqualTo("Sure."); - } - } diff --git a/exercises/practice/book-store/src/test/java/BookStoreTest.java b/exercises/practice/book-store/src/test/java/BookStoreTest.java index bbcbbcfb9..e740ce07c 100644 --- a/exercises/practice/book-store/src/test/java/BookStoreTest.java +++ b/exercises/practice/book-store/src/test/java/BookStoreTest.java @@ -1,20 +1,17 @@ -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; public class BookStoreTest { - // This is sufficient accuracy since we're handling currency values, which should be equal - // to within 2 decimal places. - private static final double EQUALITY_TOLERANCE = 0.001; + // A 0.01 tolerance covers minor rounding variations in floating point calculations + private static final double EQUALITY_TOLERANCE = 0.01; private BookStore bookStore; @@ -26,163 +23,178 @@ public void setUp() { @Test @DisplayName("Only a single book") public void onlyASingleBook() { - List books = Collections.singletonList(1); + List books = List.of(1); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(8.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(8.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two of the same book") - public void twoOfSameBook() { - List books = Arrays.asList(2, 2); + public void twoOfTheSameBook() { + List books = List.of(2, 2); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(16.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(16.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Empty basket") public void emptyBasket() { - List books = Collections.emptyList(); + List books = List.of(); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(0.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(0.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two different books") public void twoDifferentBooks() { - List books = Arrays.asList(1, 2); + List books = List.of(1, 2); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(15.20, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(15.20, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Three different books") public void threeDifferentBooks() { - List books = Arrays.asList(1, 2, 3); + List books = List.of(1, 2, 3); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(21.60, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(21.60, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Four different books") public void fourDifferentBooks() { - List books = Arrays.asList(1, 2, 3, 4); + List books = List.of(1, 2, 3, 4); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(25.60, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(25.60, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Five different books") public void fiveDifferentBooks() { - List books = Arrays.asList(1, 2, 3, 4, 5); + List books = List.of(1, 2, 3, 4, 5); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(30.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(30.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two groups of four is cheaper than group of five plus group of three") public void twoGroupsOfFourIsCheaperThanGroupOfFivePlusGroupOfThree() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5); + List books = List.of(1, 1, 2, 2, 3, 3, 4, 5); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(51.20, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(51.20, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two groups of four is cheaper than groups of five and three") public void twoGroupsOfFourIsCheaperThanGroupsOfFiveAndThree() { - List books = Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5); + List books = List.of(1, 1, 2, 3, 4, 4, 5, 5); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(51.20, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(51.20, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Group of four plus group of two is cheaper than two groups of three") public void groupOfFourPlusGroupOfTwoIsCheaperThanTwoGroupsOfThree() { - List books = Arrays.asList(1, 1, 2, 2, 3, 4); + List books = List.of(1, 1, 2, 2, 3, 4); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(40.80, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(40.80, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two each of first four books and one copy each of rest") - public void twoEachOfFirst4BooksAnd1CopyEachOfRest() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5); + public void twoEachOfFirstFourBooksAndOneCopyEachOfRest() { + List books = List.of( + 1, 1, 2, 2, 3, 3, 4, 4, 5 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(55.60, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(55.60, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Two copies of each book") public void twoCopiesOfEachBook() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5); + List books = List.of( + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(60.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(60.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Three copies of first book and two each of remaining") public void threeCopiesOfFirstBookAndTwoEachOfRemaining() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1); + List books = List.of( + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(68.00, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(68.00, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Three each of first two books and two each of remaining books") public void threeEachOfFirstTwoBooksAndTwoEachOfRemainingBooks() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2); + List books = List.of( + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(75.20, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(75.20, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("Four groups of four are cheaper than two groups each of five and three") public void fourGroupsOfFourAreCheaperThanTwoGroupsEachOfFiveAndThree() { - List books = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5, 1, 1, 2, 2, 3, 3, 4, 5); + List books = List.of( + 1, 1, 2, 2, 3, 3, 4, 5, 1, 1, 2, 2, 3, 3, 4, 5 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(102.4, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(102.40, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test - @DisplayName( - "Check that groups of four are created properly even when there are more groups of three than groups of five" - ) - public void groupsOfFourAreCreatedEvenWhenThereAreMoreGroupsOfThreeThanGroupsOfFive() { - List books = Arrays.asList(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5); + @DisplayName("Check that groups of four are created properly even when there are " + + "more groups of three than groups of five") + public void checkThatGroupsOfFourAreCreatedProperlyEvenWhenThereAreMoreGroups() { + List books = List.of( + 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(145.6, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(145.60, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test @DisplayName("One group of one and four is cheaper than one group of two and three") public void oneGroupOfOneAndFourIsCheaperThanOneGroupOfTwoAndThree() { - List books = Arrays.asList(1, 1, 2, 3, 4); + List books = List.of(1, 1, 2, 3, 4); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(33.6, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(33.60, offset(EQUALITY_TOLERANCE)); } @Disabled("Remove to run test") @Test - @DisplayName("One group of one and two plus three groups of four is cheaper than one group of each size") - public void oneGroupOfOneAndTwoPlusThreeGroupsOfFourIsCheaperThanOneGroupOfEachSize() { - List books = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5); + @DisplayName("One group of one and two plus three groups of four is cheaper than one " + + "group of each size") + public void oneGroupOfOneAndTwoPlusThreeGroupsOfFourIsCheaperThanOneGroupOfEa() { + List books = List.of( + 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 + ); assertThat(bookStore.calculateBasketCost(books)) - .isCloseTo(100.0, Assertions.offset(EQUALITY_TOLERANCE)); + .isCloseTo(100.00, offset(EQUALITY_TOLERANCE)); } + } diff --git a/exercises/practice/bottle-song/src/test/java/BottleSongTest.java b/exercises/practice/bottle-song/src/test/java/BottleSongTest.java index 7d5ce0a97..28ec60aca 100644 --- a/exercises/practice/bottle-song/src/test/java/BottleSongTest.java +++ b/exercises/practice/bottle-song/src/test/java/BottleSongTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,154 +6,142 @@ public class BottleSongTest { - private BottleSong bottleSong; - - @BeforeEach - public void setup() { - bottleSong = new BottleSong(); - } + private BottleSong bottleSong = new BottleSong(); @Test - @DisplayName("first generic verse") - public void firstGenericVerse() { - assertThat(bottleSong.recite(10, 1)).isEqualTo( - "Ten green bottles hanging on the wall,\n" + - "Ten green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be nine green bottles hanging on the wall.\n" - ); + @DisplayName("verse -> single verse -> first generic verse") + public void verseSingleVerseFirstGenericVerse() { + assertThat(bottleSong.recite(10, 1)) + .isEqualTo("Ten green bottles hanging on the wall,\n" + + "Ten green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be nine green bottles hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("last generic verse") - public void lastGenericVerse() { - assertThat(bottleSong.recite(3, 1)).isEqualTo( - "Three green bottles hanging on the wall,\n" + - "Three green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be two green bottles hanging on the wall.\n" - ); + @DisplayName("verse -> single verse -> last generic verse") + public void verseSingleVerseLastGenericVerse() { + assertThat(bottleSong.recite(3, 1)) + .isEqualTo("Three green bottles hanging on the wall,\n" + + "Three green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be two green bottles hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("verse with 2 bottles") - public void verseWithTwoBottles() { - assertThat(bottleSong.recite(2, 1)).isEqualTo( - "Two green bottles hanging on the wall,\n" + - "Two green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be one green bottle hanging on the wall.\n" - ); + @DisplayName("verse -> single verse -> verse with 2 bottles") + public void verseSingleVerseVerseWith2Bottles() { + assertThat(bottleSong.recite(2, 1)) + .isEqualTo("Two green bottles hanging on the wall,\n" + + "Two green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be one green bottle hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("verse with 1 bottle") - public void verseWithOneBottle() { - assertThat(bottleSong.recite(1, 1)).isEqualTo( - "One green bottle hanging on the wall,\n" + - "One green bottle hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be no green bottles hanging on the wall.\n" - ); + @DisplayName("verse -> single verse -> verse with 1 bottle") + public void verseSingleVerseVerseWith1Bottle() { + assertThat(bottleSong.recite(1, 1)) + .isEqualTo("One green bottle hanging on the wall,\n" + + "One green bottle hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be no green bottles hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("first two verses") - public void firstTwoVerses() { - assertThat(bottleSong.recite(10, 2)).isEqualTo( - "Ten green bottles hanging on the wall,\n" + - "Ten green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be nine green bottles hanging on the wall.\n" + - "\n" + - "Nine green bottles hanging on the wall,\n" + - "Nine green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be eight green bottles hanging on the wall.\n" - ); + @DisplayName("lyrics -> multiple verses -> first two verses") + public void lyricsMultipleVersesFirstTwoVerses() { + assertThat(bottleSong.recite(10, 2)) + .isEqualTo("Ten green bottles hanging on the wall,\n" + + "Ten green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be nine green bottles hanging on the wall.\n" + + "\n" + + "Nine green bottles hanging on the wall,\n" + + "Nine green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be eight green bottles hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("last three verses") - public void lastThreeVerses() { - assertThat(bottleSong.recite(3, 3)).isEqualTo( - "Three green bottles hanging on the wall,\n" + - "Three green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be two green bottles hanging on the wall.\n" + - "\n" + - "Two green bottles hanging on the wall,\n" + - "Two green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be one green bottle hanging on the wall.\n" + - "\n" + - "One green bottle hanging on the wall,\n" + - "One green bottle hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be no green bottles hanging on the wall.\n" - ); + @DisplayName("lyrics -> multiple verses -> last three verses") + public void lyricsMultipleVersesLastThreeVerses() { + assertThat(bottleSong.recite(3, 3)) + .isEqualTo("Three green bottles hanging on the wall,\n" + + "Three green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be two green bottles hanging on the wall.\n" + + "\n" + + "Two green bottles hanging on the wall,\n" + + "Two green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be one green bottle hanging on the wall.\n" + + "\n" + + "One green bottle hanging on the wall,\n" + + "One green bottle hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be no green bottles hanging on the wall.\n"); } @Disabled("Remove to run test") @Test - @DisplayName("all verses") - public void allVerses() { + @DisplayName("lyrics -> multiple verses -> all verses") + public void lyricsMultipleVersesAllVerses() { assertThat(bottleSong.recite(10, 10)) - .isEqualTo( - "Ten green bottles hanging on the wall,\n" + - "Ten green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be nine green bottles hanging on the wall.\n" + - "\n" + - "Nine green bottles hanging on the wall,\n" + - "Nine green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be eight green bottles hanging on the wall.\n" + - "\n" + - "Eight green bottles hanging on the wall,\n" + - "Eight green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be seven green bottles hanging on the wall.\n" + - "\n" + - "Seven green bottles hanging on the wall,\n" + - "Seven green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be six green bottles hanging on the wall.\n" + - "\n" + - "Six green bottles hanging on the wall,\n" + - "Six green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be five green bottles hanging on the wall.\n" + - "\n" + - "Five green bottles hanging on the wall,\n" + - "Five green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be four green bottles hanging on the wall.\n" + - "\n" + - "Four green bottles hanging on the wall,\n" + - "Four green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be three green bottles hanging on the wall.\n" + - "\n" + - "Three green bottles hanging on the wall,\n" + - "Three green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be two green bottles hanging on the wall.\n" + - "\n" + - "Two green bottles hanging on the wall,\n" + - "Two green bottles hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be one green bottle hanging on the wall.\n" + - "\n" + - "One green bottle hanging on the wall,\n" + - "One green bottle hanging on the wall,\n" + - "And if one green bottle should accidentally fall,\n" + - "There'll be no green bottles hanging on the wall.\n" - ); + .isEqualTo("Ten green bottles hanging on the wall,\n" + + "Ten green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be nine green bottles hanging on the wall.\n" + + "\n" + + "Nine green bottles hanging on the wall,\n" + + "Nine green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be eight green bottles hanging on the wall.\n" + + "\n" + + "Eight green bottles hanging on the wall,\n" + + "Eight green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be seven green bottles hanging on the wall.\n" + + "\n" + + "Seven green bottles hanging on the wall,\n" + + "Seven green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be six green bottles hanging on the wall.\n" + + "\n" + + "Six green bottles hanging on the wall,\n" + + "Six green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be five green bottles hanging on the wall.\n" + + "\n" + + "Five green bottles hanging on the wall,\n" + + "Five green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be four green bottles hanging on the wall.\n" + + "\n" + + "Four green bottles hanging on the wall,\n" + + "Four green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be three green bottles hanging on the wall.\n" + + "\n" + + "Three green bottles hanging on the wall,\n" + + "Three green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be two green bottles hanging on the wall.\n" + + "\n" + + "Two green bottles hanging on the wall,\n" + + "Two green bottles hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be one green bottle hanging on the wall.\n" + + "\n" + + "One green bottle hanging on the wall,\n" + + "One green bottle hanging on the wall,\n" + + "And if one green bottle should accidentally fall,\n" + + "There'll be no green bottles hanging on the wall.\n"); } + } diff --git a/exercises/practice/bowling/src/test/java/BowlingGameTest.java b/exercises/practice/bowling/src/test/java/BowlingGameTest.java index a8fbcad96..d52775575 100644 --- a/exercises/practice/bowling/src/test/java/BowlingGameTest.java +++ b/exercises/practice/bowling/src/test/java/BowlingGameTest.java @@ -6,30 +6,33 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class BowlingGameTest { - private BowlingGame game = new BowlingGame(); - - private void playGame(int[] rolls) { - for (int pins : rolls) { - game.roll(pins); - } - } @Test @DisplayName("should be able to score a game with all zeros") public void shouldBeAbleToScoreAGameWithAllZeros() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); - assertThat(game.score()).isZero(); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } + assertThat(game.score()).isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("should be able to score a game with no strikes or spares") public void shouldBeAbleToScoreAGameWithNoStrikesOrSpares() { - int[] rolls = {3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, + 3, 6, 3, 6, 3, 6, 3, 6, 3, 6 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(90); } @@ -37,9 +40,14 @@ public void shouldBeAbleToScoreAGameWithNoStrikesOrSpares() { @Test @DisplayName("a spare followed by zeros is worth ten points") public void aSpareFollowedByZerosIsWorthTenPoints() { - int[] rolls = {6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(10); } @@ -47,9 +55,14 @@ public void aSpareFollowedByZerosIsWorthTenPoints() { @Test @DisplayName("points scored in the roll after a spare are counted twice") public void pointsScoredInTheRollAfterASpareAreCountedTwice() { - int[] rolls = {6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 6, 4, 3, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(16); } @@ -57,9 +70,14 @@ public void pointsScoredInTheRollAfterASpareAreCountedTwice() { @Test @DisplayName("consecutive spares each get a one roll bonus") public void consecutiveSparesEachGetAOneRollBonus() { - int[] rolls = {5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 5, 5, 3, 7, 4, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(31); } @@ -67,19 +85,30 @@ public void consecutiveSparesEachGetAOneRollBonus() { @Test @DisplayName("a spare in the last frame gets a one roll bonus that is counted once") public void aSpareInTheLastFrameGetsAOneRollBonusThatIsCountedOnce() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, + 7 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(17); } @Disabled("Remove to run test") @Test @DisplayName("a strike earns ten points in a frame with a single roll") - public void aStrikeEarnsTenPointsInFrameWithASingleRoll() { - int[] rolls = {10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + public void aStrikeEarnsTenPointsInAFrameWithASingleRoll() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(10); } @@ -87,9 +116,14 @@ public void aStrikeEarnsTenPointsInFrameWithASingleRoll() { @Test @DisplayName("points scored in the two rolls after a strike are counted twice as a bonus") public void pointsScoredInTheTwoRollsAfterAStrikeAreCountedTwiceAsABonus() { - int[] rolls = {10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(26); } @@ -97,9 +131,14 @@ public void pointsScoredInTheTwoRollsAfterAStrikeAreCountedTwiceAsABonus() { @Test @DisplayName("consecutive strikes each get the two roll bonus") public void consecutiveStrikesEachGetTheTwoRollBonus() { - int[] rolls = {10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 10, 10, 10, 5, 3, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(81); } @@ -107,9 +146,15 @@ public void consecutiveStrikesEachGetTheTwoRollBonus() { @Test @DisplayName("a strike in the last frame gets a two roll bonus that is counted once") public void aStrikeInTheLastFrameGetsATwoRollBonusThatIsCountedOnce() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, + 1 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(18); } @@ -117,9 +162,15 @@ public void aStrikeInTheLastFrameGetsATwoRollBonusThatIsCountedOnce() { @Test @DisplayName("rolling a spare with the two roll bonus does not get a bonus roll") public void rollingASpareWithTheTwoRollBonusDoesNotGetABonusRoll() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, + 3 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(20); } @@ -127,9 +178,15 @@ public void rollingASpareWithTheTwoRollBonusDoesNotGetABonusRoll() { @Test @DisplayName("strikes with the two roll bonus do not get bonus rolls") public void strikesWithTheTwoRollBonusDoNotGetBonusRolls() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, + 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(30); } @@ -137,19 +194,30 @@ public void strikesWithTheTwoRollBonusDoNotGetBonusRolls() { @Test @DisplayName("last two strikes followed by only last bonus with non strike points") public void lastTwoStrikesFollowedByOnlyLastBonusWithNonStrikePoints() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 0, 1}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 10, 10, 0, 1 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(31); } @Disabled("Remove to run test") @Test @DisplayName("a strike with the one roll bonus after a spare in the last frame does not get a bonus") - public void aStrikeWithTheOneRollBonusAfterASpareInTheLastFrameDoesNotGetABonus() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10}; - - playGame(rolls); + public void aStrikeWithTheOneRollBonusAfterASpareInTheLastFrameDoesNotGetABon() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, + 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(20); } @@ -157,197 +225,278 @@ public void aStrikeWithTheOneRollBonusAfterASpareInTheLastFrameDoesNotGetABonus( @Test @DisplayName("all strikes is a perfect game") public void allStrikesIsAPerfectGame() { - int[] rolls = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; - - playGame(rolls); + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(300); } @Disabled("Remove to run test") @Test @DisplayName("rolls cannot score negative points") - public void rollsCanNotScoreNegativePoints() { - int[] rolls = {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - + public void rollsCannotScoreNegativePoints() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{}; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Negative roll is invalid"); + .isThrownBy(() -> game.roll(-1)) + .withMessage("Negative roll is invalid"); } @Disabled("Remove to run test") @Test @DisplayName("a roll cannot score more than 10 points") - public void aRollCanNotScoreMoreThan10Points() { - int[] rolls = {11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - + public void aRollCannotScoreMoreThan10Points() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{}; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(11)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test @DisplayName("two rolls in a frame cannot score more than 10 points") - public void twoRollsInAFrameCanNotScoreMoreThan10Points() { - int[] rolls = {5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - + public void twoRollsInAFrameCannotScoreMoreThan10Points() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{5}; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(6)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test @DisplayName("bonus roll after a strike in the last frame cannot score more than 10 points") - public void bonusRollAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 0}; - + public void bonusRollAfterAStrikeInTheLastFrameCannotScoreMoreThan10Points() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(11)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test @DisplayName("two bonus rolls after a strike in the last frame cannot score more than 10 points") - public void twoBonusRollsAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5, 6}; - + public void twoBonusRollsAfterAStrikeInTheLastFrameCannotScoreMoreThan10Point() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 5 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(6)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test - @DisplayName("two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike") - public void twoBonusRollsAfterAStrikeInTheLastFrameCanScoreMoreThan10PointsIfOneIsAStrike() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6}; - - playGame(rolls); - + @DisplayName("two bonus rolls after a strike in the last frame can score more than " + + "10 points if one is a strike") + public void twoBonusRollsAfterAStrikeInTheLastFrameCanScoreMoreThan10PointsIf() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, + 6 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThat(game.score()).isEqualTo(26); } @Disabled("Remove to run test") @Test - @DisplayName( - "the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike" - ) - public void theSecondBonusRollsAfterAStrikeInTheLastFrameCanNotBeAStrikeIfTheFirstOneIsNotAStrike() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6, 10}; - + @DisplayName("the second bonus rolls after a strike in the last frame cannot be a " + + "strike if the first one is not a strike") + public void theSecondBonusRollsAfterAStrikeInTheLastFrameCannotBeAStrikeIfThe() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 6 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(10)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test @DisplayName("second bonus roll after a strike in the last frame cannot score more than 10 points") - public void secondBonusRollAfterAStrikeInTheLastFrameCanNotScoreMoreThan10Points() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 11}; - + public void secondBonusRollAfterAStrikeInTheLastFrameCannotScoreMoreThan10Poi() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Pin count exceeds pins on the lane"); + .isThrownBy(() -> game.roll(11)) + .withMessage("Pin count exceeds pins on the lane"); } @Disabled("Remove to run test") @Test @DisplayName("an unstarted game cannot be scored") - public void anUnstartedGameCanNotBeScored() { - int[] rolls = new int[0]; - - playGame(rolls); - + public void anUnstartedGameCannotBeScored() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{}; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(game::score) - .withMessage("Score cannot be taken until the end of the game"); + .isThrownBy(game::score) + .withMessage("Score cannot be taken until the end of the game"); } @Disabled("Remove to run test") @Test @DisplayName("an incomplete game cannot be scored") - public void anIncompleteGameCanNotBeScored() { - int[] rolls = {0, 0}; - - playGame(rolls); - + public void anIncompleteGameCannotBeScored() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{0, 0}; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(game::score) - .withMessage("Score cannot be taken until the end of the game"); + .isThrownBy(game::score) + .withMessage("Score cannot be taken until the end of the game"); } @Disabled("Remove to run test") @Test @DisplayName("cannot roll if game already has ten frames") - public void canNotRollIfGameAlreadyHasTenFrames() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - + public void cannotRollIfGameAlreadyHasTenFrames() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Cannot roll after game is over"); + .isThrownBy(() -> game.roll(0)) + .withMessage("Cannot roll after game is over"); } @Disabled("Remove to run test") @Test - @DisplayName("bonus rolls for a strike in the last frame must be rolled before score can be calculated") - public void bonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10}; - - playGame(rolls); - + @DisplayName("bonus rolls for a strike in the last frame must be rolled before score " + + "can be calculated") + public void bonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCal() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(game::score) - .withMessage("Score cannot be taken until the end of the game"); + .isThrownBy(game::score) + .withMessage("Score cannot be taken until the end of the game"); } @Disabled("Remove to run test") @Test - @DisplayName("both bonus rolls for a strike in the last frame must be rolled before score can be calculated") - public void bothBonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10}; - - playGame(rolls); - + @DisplayName("both bonus rolls for a strike in the last frame must be rolled before " + + "score can be calculated") + public void bothBonusRollsForAStrikeInTheLastFrameMustBeRolledBeforeScoreCanB() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(game::score) - .withMessage("Score cannot be taken until the end of the game"); + .isThrownBy(game::score) + .withMessage("Score cannot be taken until the end of the game"); } @Disabled("Remove to run test") @Test - @DisplayName("bonus roll for a spare in the last frame must be rolled before score can be calculated") - public void bonusRollForASpareInTheLastFrameMustBeRolledBeforeScoreCanBeCalculated() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3}; - - playGame(rolls); - + @DisplayName("bonus roll for a spare in the last frame must be rolled before score " + + "can be calculated") + public void bonusRollForASpareInTheLastFrameMustBeRolledBeforeScoreCanBeCalcu() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 7, 3 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(game::score) - .withMessage("Score cannot be taken until the end of the game"); + .isThrownBy(game::score) + .withMessage("Score cannot be taken until the end of the game"); } @Disabled("Remove to run test") @Test @DisplayName("cannot roll after bonus roll for spare") - public void canNotRollAfterBonusRollForSpare() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 2, 2}; - + public void cannotRollAfterBonusRollForSpare() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, + 2 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Cannot roll after game is over"); + .isThrownBy(() -> game.roll(2)) + .withMessage("Cannot roll after game is over"); } @Disabled("Remove to run test") @Test @DisplayName("cannot roll after bonus rolls for strike") - public void canNotRollAfterBonusRollForStrike() { - int[] rolls = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, 2, 2}; - + public void cannotRollAfterBonusRollsForStrike() { + BowlingGame game = new BowlingGame(); + int[] rolls = new int[]{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, + 2 + }; + for (int pins : rolls) { + game.roll(pins); + } assertThatExceptionOfType(IllegalStateException.class) - .isThrownBy(() -> playGame(rolls)) - .withMessage("Cannot roll after game is over"); + .isThrownBy(() -> game.roll(2)) + .withMessage("Cannot roll after game is over"); } + } diff --git a/exercises/practice/camicia/src/test/java/CamiciaTest.java b/exercises/practice/camicia/src/test/java/CamiciaTest.java index f4f2b8e85..76476f5ca 100644 --- a/exercises/practice/camicia/src/test/java/CamiciaTest.java +++ b/exercises/practice/camicia/src/test/java/CamiciaTest.java @@ -4,11 +4,9 @@ import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class CamiciaTest { - private static final String FINISHED = "finished"; - private static final String LOOP = "loop"; @Test @DisplayName("two cards, one trick") @@ -18,9 +16,9 @@ public void twoCardsOneTrick() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(2, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(2); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -32,9 +30,9 @@ public void threeCardsOneTrick() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(3, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(3); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -46,9 +44,9 @@ public void fourCardsOneTrick() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(4, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(4); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -60,9 +58,9 @@ public void theAceReignsSupreme() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -74,9 +72,9 @@ public void theKingBeatsAce() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -88,9 +86,9 @@ public void theQueenSeducesTheKing() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(10, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(10); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -102,72 +100,90 @@ public void theJackBetraysTheQueen() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(12, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(12); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("the 10 just wants to put on a show") - public void theTenJustWantsToPutOnAShow() { + public void the10JustWantsToPutOnAShow() { List playerA = List.of("2", "A", "7", "8", "Q", "10"); List playerB = List.of("3", "4", "5", "6", "K", "9", "J"); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(13, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(13); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("simple loop with decks of 3 cards") - public void simpleLoopWithDecksOfThreeCards() { + public void simpleLoopWithDecksOf3Cards() { List playerA = List.of("J", "2", "3"); List playerB = List.of("4", "J", "5"); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(LOOP, result.status()); - assertEquals(8, result.cards()); - assertEquals(3, result.tricks()); + assertThat(result.status()).isEqualTo("loop"); + assertThat(result.cards()).isEqualTo(8); + assertThat(result.tricks()).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("the story is starting to get a bit complicated") - public void theStoryIsStartingToGetAbitComplicated() { + public void theStoryIsStartingToGetABitComplicated() { List playerA = List.of( - "2", "6", "6", "J", "4", "K", "Q", "10", "K", "J", "Q", "2", "3", "K", "5", "6", "Q", "Q", "A", "A", - "6", "9", "K", "A", "8", "K", "2", "A", "9", "A", "Q", "4", "K", "K", "K", "3", "5", "K", "8", "Q", - "3", "Q", "7", "J", "K", "J", "9", "J", "3", "3", "K", "K", "Q", "A", "K", "7", "10", "A", "Q", "7", - "10", "J", "4", "5", "J", "9", "10", "Q", "J", "J", "K", "6", "10", "J", "6", "Q", "J", "5", "J", "Q", - "Q", "8", "3", "8", "A", "2", "6", "9", "K", "7", "J", "K", "K", "8", "K", "Q", "6", "10", "J", "10", - "J", "Q", "J", "10", "3", "8", "K", "A", "6", "9", "K", "2", "A", "A", "10", "J", "6", "A", "4", "J", - "A", "J", "J", "6", "2", "J", "3", "K", "2", "5", "9", "J", "9", "6", "K", "A", "5", "Q", "J", "2", - "Q", "K", "A", "3", "K", "J", "K", "2", "5", "6", "Q", "J", "Q", "Q", "J", "2", "J", "9", "Q", "7", - "7", "A", "Q", "7", "Q", "J", "K", "J", "A", "7", "7", "8", "Q", "10", "J", "10", "J", "J", "9", "2", - "A", "2" - ); + "2", "6", "6", "J", "4", "K", "Q", "10", "K", "J", + "Q", "2", "3", "K", "5", "6", "Q", "Q", "A", "A", + "6", "9", "K", "A", "8", "K", "2", "A", "9", "A", + "Q", "4", "K", "K", "K", "3", "5", "K", "8", "Q", + "3", "Q", "7", "J", "K", "J", "9", "J", "3", "3", + "K", "K", "Q", "A", "K", "7", "10", "A", "Q", "7", + "10", "J", "4", "5", "J", "9", "10", "Q", "J", "J", + "K", "6", "10", "J", "6", "Q", "J", "5", "J", "Q", + "Q", "8", "3", "8", "A", "2", "6", "9", "K", "7", + "J", "K", "K", "8", "K", "Q", "6", "10", "J", "10", + "J", "Q", "J", "10", "3", "8", "K", "A", "6", "9", + "K", "2", "A", "A", "10", "J", "6", "A", "4", "J", + "A", "J", "J", "6", "2", "J", "3", "K", "2", "5", + "9", "J", "9", "6", "K", "A", "5", "Q", "J", "2", + "Q", "K", "A", "3", "K", "J", "K", "2", "5", "6", + "Q", "J", "Q", "Q", "J", "2", "J", "9", "Q", "7", + "7", "A", "Q", "7", "Q", "J", "K", "J", "A", "7", + "7", "8", "Q", "10", "J", "10", "J", "J", "9", "2", + "A", "2" + ); List playerB = List.of( - "7", "2", "10", "K", "8", "2", "J", "9", "A", "5", "6", "J", "Q", "6", "K", "6", "5", "A", "4", "Q", - "7", "J", "7", "10", "2", "Q", "8", "2", "2", "K", "J", "A", "5", "5", "A", "4", "Q", "6", "Q", "K", - "10", "8", "Q", "2", "10", "J", "A", "Q", "8", "Q", "Q", "J", "J", "A", "A", "9", "10", "J", "K", "4", - "Q", "10", "10", "J", "K", "10", "2", "J", "7", "A", "K", "K", "J", "A", "J", "10", "8", "K", "A", "7", - "Q", "Q", "J", "3", "Q", "4", "A", "3", "A", "Q", "Q", "Q", "5", "4", "K", "J", "10", "A", "Q", "J", - "6", "J", "A", "10", "A", "5", "8", "3", "K", "5", "9", "Q", "8", "7", "7", "J", "7", "Q", "Q", "Q", - "A", "7", "8", "9", "A", "Q", "A", "K", "8", "A", "A", "J", "8", "4", "8", "K", "J", "A", "10", "Q", - "8", "J", "8", "6", "10", "Q", "J", "J", "A", "A", "J", "5", "Q", "6", "J", "K", "Q", "8", "K", "4", - "Q", "Q", "6", "J", "K", "4", "7", "J", "J", "9", "9", "A", "Q", "Q", "K", "A", "6", "5", "K" - ); + "7", "2", "10", "K", "8", "2", "J", "9", "A", "5", + "6", "J", "Q", "6", "K", "6", "5", "A", "4", "Q", + "7", "J", "7", "10", "2", "Q", "8", "2", "2", "K", + "J", "A", "5", "5", "A", "4", "Q", "6", "Q", "K", + "10", "8", "Q", "2", "10", "J", "A", "Q", "8", "Q", + "Q", "J", "J", "A", "A", "9", "10", "J", "K", "4", + "Q", "10", "10", "J", "K", "10", "2", "J", "7", "A", + "K", "K", "J", "A", "J", "10", "8", "K", "A", "7", + "Q", "Q", "J", "3", "Q", "4", "A", "3", "A", "Q", + "Q", "Q", "5", "4", "K", "J", "10", "A", "Q", "J", + "6", "J", "A", "10", "A", "5", "8", "3", "K", "5", + "9", "Q", "8", "7", "7", "J", "7", "Q", "Q", "Q", + "A", "7", "8", "9", "A", "Q", "A", "K", "8", "A", + "A", "J", "8", "4", "8", "K", "J", "A", "10", "Q", + "8", "J", "8", "6", "10", "Q", "J", "J", "A", "A", + "J", "5", "Q", "6", "J", "K", "Q", "8", "K", "4", + "Q", "Q", "6", "J", "K", "4", "7", "J", "J", "9", + "9", "A", "Q", "Q", "K", "A", "6", "5", "K" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(361, result.cards()); - assertEquals(1, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(361); + assertThat(result.tricks()).isEqualTo(1); } @Disabled("Remove to run test") @@ -179,9 +195,9 @@ public void twoTricks() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(5, result.cards()); - assertEquals(2, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(5); + assertThat(result.tricks()).isEqualTo(2); } @Disabled("Remove to run test") @@ -193,23 +209,23 @@ public void moreTricks() { CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(12, result.cards()); - assertEquals(4, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(12); + assertThat(result.tricks()).isEqualTo(4); } @Disabled("Remove to run test") @Test @DisplayName("simple loop with decks of 4 cards") - public void simpleLoopWithDecksOfFourCards() { + public void simpleLoopWithDecksOf4Cards() { List playerA = List.of("2", "3", "J", "6"); List playerB = List.of("K", "5", "J", "7"); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(LOOP, result.status()); - assertEquals(16, result.cards()); - assertEquals(4, result.tricks()); + assertThat(result.status()).isEqualTo("loop"); + assertThat(result.cards()).isEqualTo(16); + assertThat(result.tricks()).isEqualTo(4); } @Disabled("Remove to run test") @@ -217,19 +233,21 @@ public void simpleLoopWithDecksOfFourCards() { @DisplayName("easy card combination") public void easyCardCombination() { List playerA = List.of( - "4", "8", "7", "5", "4", "10", "3", "9", "7", "3", "10", "10", "6", "8", "2", "8", "5", "4", "5", - "9", "6", "5", "2", "8", "10", "9" - ); + "4", "8", "7", "5", "4", "10", "3", "9", "7", "3", + "10", "10", "6", "8", "2", "8", "5", "4", "5", "9", + "6", "5", "2", "8", "10", "9" + ); List playerB = List.of( - "6", "9", "4", "7", "2", "2", "3", "6", "7", "3", "A", "A", "A", "A", "K", "K", "K", "K", "Q", "Q", - "Q", "Q", "J", "J", "J", "J" - ); + "6", "9", "4", "7", "2", "2", "3", "6", "7", "3", + "A", "A", "A", "A", "K", "K", "K", "K", "Q", "Q", + "Q", "Q", "J", "J", "J", "J" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(40, result.cards()); - assertEquals(4, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(40); + assertThat(result.tricks()).isEqualTo(4); } @Disabled("Remove to run test") @@ -237,19 +255,21 @@ public void easyCardCombination() { @DisplayName("easy card combination, inverted decks") public void easyCardCombinationInvertedDecks() { List playerA = List.of( - "3", "3", "5", "7", "3", "2", "10", "7", "6", "7", "A", "A", "A", "A", "K", "K", "K", "K", "Q", - "Q", "Q", "Q", "J", "J", "J", "J" - ); + "3", "3", "5", "7", "3", "2", "10", "7", "6", "7", + "A", "A", "A", "A", "K", "K", "K", "K", "Q", "Q", + "Q", "Q", "J", "J", "J", "J" + ); List playerB = List.of( - "5", "10", "8", "2", "6", "7", "2", "4", "9", "2", "6", "10", "10", "5", "4", "8", "4", "8", "6", - "9", "8", "5", "9", "3", "4", "9" - ); + "5", "10", "8", "2", "6", "7", "2", "4", "9", "2", + "6", "10", "10", "5", "4", "8", "4", "8", "6", "9", + "8", "5", "9", "3", "4", "9" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(40, result.cards()); - assertEquals(4, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(40); + assertThat(result.tricks()).isEqualTo(4); } @Disabled("Remove to run test") @@ -257,19 +277,21 @@ public void easyCardCombinationInvertedDecks() { @DisplayName("mirrored decks") public void mirroredDecks() { List playerA = List.of( - "2", "A", "3", "A", "3", "K", "4", "K", "2", "Q", "2", "Q", "10", "J", "5", "J", "6", "10", "2", - "9", "10", "7", "3", "9", "6", "9" - ); + "2", "A", "3", "A", "3", "K", "4", "K", "2", "Q", + "2", "Q", "10", "J", "5", "J", "6", "10", "2", "9", + "10", "7", "3", "9", "6", "9" + ); List playerB = List.of( - "6", "A", "4", "A", "7", "K", "4", "K", "7", "Q", "7", "Q", "5", "J", "8", "J", "4", "5", "8", - "9", "10", "6", "8", "3", "8", "5" - ); + "6", "A", "4", "A", "7", "K", "4", "K", "7", "Q", + "7", "Q", "5", "J", "8", "J", "4", "5", "8", "9", + "10", "6", "8", "3", "8", "5" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(59, result.cards()); - assertEquals(4, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(59); + assertThat(result.tricks()).isEqualTo(4); } @Disabled("Remove to run test") @@ -277,59 +299,65 @@ public void mirroredDecks() { @DisplayName("opposite decks") public void oppositeDecks() { List playerA = List.of( - "4", "A", "9", "A", "4", "K", "9", "K", "6", "Q", "8", "Q", "8", "J", "10", "J", "9", "8", "4", - "6", "3", "6", "5", "2", "4", "3" - ); + "4", "A", "9", "A", "4", "K", "9", "K", "6", "Q", + "8", "Q", "8", "J", "10", "J", "9", "8", "4", "6", + "3", "6", "5", "2", "4", "3" + ); List playerB = List.of( - "10", "7", "3", "2", "9", "2", "7", "8", "7", "5", "J", "7", "J", "10", "Q", "10", "Q", "3", "K", - "5", "K", "6", "A", "2", "A", "5" - ); + "10", "7", "3", "2", "9", "2", "7", "8", "7", "5", + "J", "7", "J", "10", "Q", "10", "Q", "3", "K", "5", + "K", "6", "A", "2", "A", "5" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(151, result.cards()); - assertEquals(21, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(151); + assertThat(result.tricks()).isEqualTo(21); } @Disabled("Remove to run test") @Test @DisplayName("random decks #1") - public void randomDecksOne() { + public void randomDecks1() { List playerA = List.of( - "K", "10", "9", "8", "J", "8", "6", "9", "7", "A", "K", "5", "4", "4", "J", "5", "J", "4", "3", - "5", "8", "6", "7", "7", "4", "9" - ); + "K", "10", "9", "8", "J", "8", "6", "9", "7", "A", + "K", "5", "4", "4", "J", "5", "J", "4", "3", "5", + "8", "6", "7", "7", "4", "9" + ); List playerB = List.of( - "6", "3", "K", "A", "Q", "10", "A", "2", "Q", "8", "2", "10", "10", "2", "Q", "3", "K", "9", "7", - "A", "3", "Q", "5", "J", "2", "6" - ); + "6", "3", "K", "A", "Q", "10", "A", "2", "Q", "8", + "2", "10", "10", "2", "Q", "3", "K", "9", "7", "A", + "3", "Q", "5", "J", "2", "6" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(542, result.cards()); - assertEquals(76, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(542); + assertThat(result.tricks()).isEqualTo(76); } @Disabled("Remove to run test") @Test @DisplayName("random decks #2") - public void randomDecksTwo() { + public void randomDecks2() { List playerA = List.of( - "8", "A", "4", "8", "5", "Q", "J", "2", "6", "2", "9", "7", "K", "A", "8", "10", "K", "8", "10", - "9", "K", "6", "7", "3", "K", "9" - ); + "8", "A", "4", "8", "5", "Q", "J", "2", "6", "2", + "9", "7", "K", "A", "8", "10", "K", "8", "10", "9", + "K", "6", "7", "3", "K", "9" + ); List playerB = List.of( - "10", "5", "2", "6", "Q", "J", "A", "9", "5", "5", "3", "7", "3", "J", "A", "2", "Q", "3", "J", - "Q", "4", "10", "4", "7", "4", "6" - ); + "10", "5", "2", "6", "Q", "J", "A", "9", "5", "5", + "3", "7", "3", "J", "A", "2", "Q", "3", "J", "Q", + "4", "10", "4", "7", "4", "6" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(327, result.cards()); - assertEquals(42, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(327); + assertThat(result.tricks()).isEqualTo(42); } @Disabled("Remove to run test") @@ -337,19 +365,21 @@ public void randomDecksTwo() { @DisplayName("Kleber 1999") public void kleber1999() { List playerA = List.of( - "4", "8", "9", "J", "Q", "8", "5", "5", "K", "2", "A", "9", "8", "5", "10", "A", "4", "J", "3", - "K", "6", "9", "2", "Q", "K", "7" - ); + "4", "8", "9", "J", "Q", "8", "5", "5", "K", "2", + "A", "9", "8", "5", "10", "A", "4", "J", "3", "K", + "6", "9", "2", "Q", "K", "7" + ); List playerB = List.of( - "10", "J", "3", "2", "4", "10", "4", "7", "5", "3", "6", "6", "7", "A", "J", "Q", "A", "7", "2", - "10", "3", "K", "9", "6", "8", "Q" - ); + "10", "J", "3", "2", "4", "10", "4", "7", "5", "3", + "6", "6", "7", "A", "J", "Q", "A", "7", "2", "10", + "3", "K", "9", "6", "8", "Q" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(5790, result.cards()); - assertEquals(805, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(5790); + assertThat(result.tricks()).isEqualTo(805); } @Disabled("Remove to run test") @@ -357,19 +387,21 @@ public void kleber1999() { @DisplayName("Collins 2006") public void collins2006() { List playerA = List.of( - "A", "8", "Q", "K", "9", "10", "3", "7", "4", "2", "Q", "3", "2", "10", "9", "K", "A", "8", "7", - "7", "4", "5", "J", "9", "2", "10" - ); + "A", "8", "Q", "K", "9", "10", "3", "7", "4", "2", + "Q", "3", "2", "10", "9", "K", "A", "8", "7", "7", + "4", "5", "J", "9", "2", "10" + ); List playerB = List.of( - "4", "J", "A", "K", "8", "5", "6", "6", "A", "6", "5", "Q", "4", "6", "10", "8", "J", "2", "5", - "7", "Q", "J", "3", "3", "K", "9" - ); + "4", "J", "A", "K", "8", "5", "6", "6", "A", "6", + "5", "Q", "4", "6", "10", "8", "J", "2", "5", "7", + "Q", "J", "3", "3", "K", "9" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(6913, result.cards()); - assertEquals(960, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(6913); + assertThat(result.tricks()).isEqualTo(960); } @Disabled("Remove to run test") @@ -377,19 +409,21 @@ public void collins2006() { @DisplayName("Mann and Wu 2007") public void mannAndWu2007() { List playerA = List.of( - "K", "2", "K", "K", "3", "3", "6", "10", "K", "6", "A", "2", "5", "5", "7", "9", "J", "A", "A", - "3", "4", "Q", "4", "8", "J", "6" - ); + "K", "2", "K", "K", "3", "3", "6", "10", "K", "6", + "A", "2", "5", "5", "7", "9", "J", "A", "A", "3", + "4", "Q", "4", "8", "J", "6" + ); List playerB = List.of( - "4", "5", "2", "Q", "7", "9", "9", "Q", "7", "J", "9", "8", "10", "3", "10", "J", "4", "10", "8", - "6", "8", "7", "A", "Q", "5", "2" - ); + "4", "5", "2", "Q", "7", "9", "9", "Q", "7", "J", + "9", "8", "10", "3", "10", "J", "4", "10", "8", "6", + "8", "7", "A", "Q", "5", "2" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7157, result.cards()); - assertEquals(1007, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7157); + assertThat(result.tricks()).isEqualTo(1007); } @Disabled("Remove to run test") @@ -397,19 +431,21 @@ public void mannAndWu2007() { @DisplayName("Nessler 2012") public void nessler2012() { List playerA = List.of( - "10", "3", "6", "7", "Q", "2", "9", "8", "2", "8", "4", "A", "10", "6", "K", "2", "10", "A", "5", - "A", "2", "4", "Q", "J", "K", "4" - ); + "10", "3", "6", "7", "Q", "2", "9", "8", "2", "8", + "4", "A", "10", "6", "K", "2", "10", "A", "5", "A", + "2", "4", "Q", "J", "K", "4" + ); List playerB = List.of( - "10", "Q", "4", "6", "J", "9", "3", "J", "9", "3", "3", "Q", "K", "5", "9", "5", "K", "6", "5", - "7", "8", "J", "A", "7", "8", "7" - ); + "10", "Q", "4", "6", "J", "9", "3", "J", "9", "3", + "3", "Q", "K", "5", "9", "5", "K", "6", "5", "7", + "8", "J", "A", "7", "8", "7" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7207, result.cards()); - assertEquals(1015, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7207); + assertThat(result.tricks()).isEqualTo(1015); } @Disabled("Remove to run test") @@ -417,19 +453,21 @@ public void nessler2012() { @DisplayName("Anderson 2013") public void anderson2013() { List playerA = List.of( - "6", "7", "A", "3", "Q", "3", "5", "J", "3", "2", "J", "7", "4", "5", "Q", "10", "5", "A", "J", - "2", "K", "8", "9", "9", "K", "3" - ); + "6", "7", "A", "3", "Q", "3", "5", "J", "3", "2", + "J", "7", "4", "5", "Q", "10", "5", "A", "J", "2", + "K", "8", "9", "9", "K", "3" + ); List playerB = List.of( - "4", "J", "6", "9", "8", "5", "10", "7", "9", "Q", "2", "7", "10", "8", "4", "10", "A", "6", "4", - "A", "6", "8", "Q", "K", "K", "2" - ); + "4", "J", "6", "9", "8", "5", "10", "7", "9", "Q", + "2", "7", "10", "8", "4", "10", "A", "6", "4", "A", + "6", "8", "Q", "K", "K", "2" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7225, result.cards()); - assertEquals(1016, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7225); + assertThat(result.tricks()).isEqualTo(1016); } @Disabled("Remove to run test") @@ -437,19 +475,21 @@ public void anderson2013() { @DisplayName("Rucklidge 2014") public void rucklidge2014() { List playerA = List.of( - "8", "J", "2", "9", "4", "4", "5", "8", "Q", "3", "9", "3", "6", "2", "8", "A", "A", "A", "9", - "4", "7", "2", "5", "Q", "Q", "3" - ); + "8", "J", "2", "9", "4", "4", "5", "8", "Q", "3", + "9", "3", "6", "2", "8", "A", "A", "A", "9", "4", + "7", "2", "5", "Q", "Q", "3" + ); List playerB = List.of( - "K", "7", "10", "6", "3", "J", "A", "7", "6", "5", "5", "8", "10", "9", "10", "4", "2", "7", "K", - "Q", "10", "K", "6", "J", "J", "K" - ); + "K", "7", "10", "6", "3", "J", "A", "7", "6", "5", + "5", "8", "10", "9", "10", "4", "2", "7", "K", "Q", + "10", "K", "6", "J", "J", "K" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7959, result.cards()); - assertEquals(1122, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7959); + assertThat(result.tricks()).isEqualTo(1122); } @Disabled("Remove to run test") @@ -457,19 +497,21 @@ public void rucklidge2014() { @DisplayName("Nessler 2021") public void nessler2021() { List playerA = List.of( - "7", "2", "3", "4", "K", "9", "6", "10", "A", "8", "9", "Q", "7", "A", "4", "8", "J", "J", "A", - "4", "3", "2", "5", "6", "6", "J" - ); + "7", "2", "3", "4", "K", "9", "6", "10", "A", "8", + "9", "Q", "7", "A", "4", "8", "J", "J", "A", "4", + "3", "2", "5", "6", "6", "J" + ); List playerB = List.of( - "3", "10", "8", "9", "8", "K", "K", "2", "5", "5", "7", "6", "4", "3", "5", "7", "A", "9", "J", - "K", "2", "Q", "10", "Q", "10", "Q" - ); + "3", "10", "8", "9", "8", "K", "K", "2", "5", "5", + "7", "6", "4", "3", "5", "7", "A", "9", "J", "K", + "2", "Q", "10", "Q", "10", "Q" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(7972, result.cards()); - assertEquals(1106, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(7972); + assertThat(result.tricks()).isEqualTo(1106); } @Disabled("Remove to run test") @@ -477,19 +519,21 @@ public void nessler2021() { @DisplayName("Nessler 2022") public void nessler2022() { List playerA = List.of( - "2", "10", "10", "A", "J", "3", "8", "Q", "2", "5", "5", "5", "9", "2", "4", "3", "10", "Q", "A", - "K", "Q", "J", "J", "9", "Q", "K" - ); + "2", "10", "10", "A", "J", "3", "8", "Q", "2", "5", + "5", "5", "9", "2", "4", "3", "10", "Q", "A", "K", + "Q", "J", "J", "9", "Q", "K" + ); List playerB = List.of( - "10", "7", "6", "3", "6", "A", "8", "9", "4", "3", "K", "J", "6", "K", "4", "9", "7", "8", "5", - "7", "8", "2", "A", "7", "4", "6" - ); + "10", "7", "6", "3", "6", "A", "8", "9", "4", "3", + "K", "J", "6", "K", "4", "9", "7", "8", "5", "7", + "8", "2", "A", "7", "4", "6" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(FINISHED, result.status()); - assertEquals(8344, result.cards()); - assertEquals(1164, result.tricks()); + assertThat(result.status()).isEqualTo("finished"); + assertThat(result.cards()).isEqualTo(8344); + assertThat(result.tricks()).isEqualTo(1164); } @Disabled("Remove to run test") @@ -497,18 +541,21 @@ public void nessler2022() { @DisplayName("Casella 2024, first infinite game found") public void casella2024FirstInfiniteGameFound() { List playerA = List.of( - "2", "8", "4", "K", "5", "2", "3", "Q", "6", "K", "Q", "A", "J", "3", "5", "9", "8", "3", "A", - "A", "J", "4", "4", "J", "7", "5" - ); + "2", "8", "4", "K", "5", "2", "3", "Q", "6", "K", + "Q", "A", "J", "3", "5", "9", "8", "3", "A", "A", + "J", "4", "4", "J", "7", "5" + ); List playerB = List.of( - "7", "7", "8", "6", "10", "10", "6", "10", "7", "2", "Q", "6", "3", "2", "4", "K", "Q", "10", "J", - "5", "9", "8", "9", "9", "K", "A" - ); + "7", "7", "8", "6", "10", "10", "6", "10", "7", "2", + "Q", "6", "3", "2", "4", "K", "Q", "10", "J", "5", + "9", "8", "9", "9", "K", "A" + ); CamiciaResult result = Camicia.simulateGame(playerA, playerB); - assertEquals(LOOP, result.status()); - assertEquals(474, result.cards()); - assertEquals(66, result.tricks()); + assertThat(result.status()).isEqualTo("loop"); + assertThat(result.cards()).isEqualTo(474); + assertThat(result.tricks()).isEqualTo(66); } + } diff --git a/exercises/practice/change/src/test/java/ChangeCalculatorTest.java b/exercises/practice/change/src/test/java/ChangeCalculatorTest.java index b88c316d3..30573dc91 100644 --- a/exercises/practice/change/src/test/java/ChangeCalculatorTest.java +++ b/exercises/practice/change/src/test/java/ChangeCalculatorTest.java @@ -10,7 +10,7 @@ public class ChangeCalculatorTest { @Test @DisplayName("change for 1 cent") - public void testChangeForOneCent() { + public void changeFor1Cent() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25)); assertThat(changeCalculator.computeMostEfficientChange(1)) @@ -20,97 +20,97 @@ public void testChangeForOneCent() { @Disabled("Remove to run test") @Test @DisplayName("single coin change") - public void testChangeThatCanBeGivenInASingleCoin() { + public void singleCoinChange() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25, 100)); assertThat(changeCalculator.computeMostEfficientChange(25)) - .containsExactly(25); + .containsExactly(25); } @Disabled("Remove to run test") @Test @DisplayName("multiple coin change") - public void testChangeThatMustBeGivenInMultipleCoins() { + public void multipleCoinChange() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25, 100)); assertThat(changeCalculator.computeMostEfficientChange(15)) - .containsExactly(5, 10); + .containsExactly(5, 10); } @Disabled("Remove to run test") @Test @DisplayName("change with Lilliputian Coins") - public void testLilliputianCurrency() { + public void changeWithLilliputianCoins() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 4, 15, 20, 50)); assertThat(changeCalculator.computeMostEfficientChange(23)) - .containsExactly(4, 4, 15); + .containsExactly(4, 4, 15); } @Disabled("Remove to run test") @Test @DisplayName("change with Lower Elbonia Coins") - public void testLowerElbonianCurrency() { + public void changeWithLowerElboniaCoins() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 21, 25)); assertThat(changeCalculator.computeMostEfficientChange(63)) - .containsExactly(21, 21, 21); + .containsExactly(21, 21, 21); } @Disabled("Remove to run test") @Test @DisplayName("large target values") - public void testLargeAmountOfChange() { + public void largeTargetValues() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 2, 5, 10, 20, 50, 100)); assertThat(changeCalculator.computeMostEfficientChange(999)) - .containsExactly(2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100); + .containsExactly(2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100); } @Disabled("Remove to run test") @Test @DisplayName("possible change without unit coins available") - public void testPossibleChangeWithoutUnitCoinAvailable() { + public void possibleChangeWithoutUnitCoinsAvailable() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(2, 5, 10, 20, 50)); assertThat(changeCalculator.computeMostEfficientChange(21)) - .containsExactly(2, 2, 2, 5, 10); + .containsExactly(2, 2, 2, 5, 10); } @Disabled("Remove to run test") @Test @DisplayName("another possible change without unit coins available") - public void testAnotherPossibleChangeWithoutUnitCoinAvailable() { + public void anotherPossibleChangeWithoutUnitCoinsAvailable() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(4, 5)); assertThat(changeCalculator.computeMostEfficientChange(27)) - .containsExactly(4, 4, 4, 5, 5, 5); + .containsExactly(4, 4, 4, 5, 5, 5); } @Disabled("Remove to run test") @Test @DisplayName("a greedy approach is not optimal") - public void testAGreedyApproachIsNotOptimal() { + public void aGreedyApproachIsNotOptimal() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 10, 11)); assertThat(changeCalculator.computeMostEfficientChange(20)) - .containsExactly(10, 10); + .containsExactly(10, 10); } @Disabled("Remove to run test") @Test @DisplayName("no coins make 0 change") - public void testZeroChange() { + public void noCoinsMake0Change() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 21, 25)); assertThat(changeCalculator.computeMostEfficientChange(0)) - .isEmpty(); + .isEmpty(); } @Disabled("Remove to run test") @Test @DisplayName("error testing for change smaller than the smallest of coins") - public void testChangeLessThanSmallestCoinInCurrencyCannotBeRepresented() { + public void errorTestingForChangeSmallerThanTheSmallestOfCoins() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(5, 10)); assertThatExceptionOfType(IllegalArgumentException.class) @@ -121,7 +121,7 @@ public void testChangeLessThanSmallestCoinInCurrencyCannotBeRepresented() { @Disabled("Remove to run test") @Test @DisplayName("error if no combination can add up to target") - public void testChangeLargerThanAllCoinsInCurrencyThatCannotBeRepresented() { + public void errorIfNoCombinationCanAddUpToTarget() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(5, 10)); assertThatExceptionOfType(IllegalArgumentException.class) @@ -132,7 +132,7 @@ public void testChangeLargerThanAllCoinsInCurrencyThatCannotBeRepresented() { @Disabled("Remove to run test") @Test @DisplayName("cannot find negative change values") - public void testNegativeChangeIsRejected() { + public void cannotFindNegativeChangeValues() { ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 2, 5)); assertThatExceptionOfType(IllegalArgumentException.class) diff --git a/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java b/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java index 6ecbc1930..fc818c0b4 100644 --- a/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java +++ b/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java @@ -1,15 +1,15 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class CircularBufferTest { @Test @DisplayName("reading empty buffer should fail") - public void readingFromEmptyBufferShouldThrowException() { + public void readingEmptyBufferShouldFail() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); assertThatExceptionOfType(BufferIOException.class) @@ -20,20 +20,22 @@ public void readingFromEmptyBufferShouldThrowException() { @Disabled("Remove to run test") @Test @DisplayName("can read an item just written") - public void canReadItemJustWritten() throws BufferIOException { + public void canReadAnItemJustWritten() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); + assertThat(buffer.read()).isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("each item may only be read once") - public void canReadItemOnlyOnce() throws BufferIOException { + public void eachItemMayOnlyBeReadOnce() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); + assertThat(buffer.read()).isEqualTo(1); assertThatExceptionOfType(BufferIOException.class) @@ -44,19 +46,22 @@ public void canReadItemOnlyOnce() throws BufferIOException { @Disabled("Remove to run test") @Test @DisplayName("items are read in the order they are written") - public void readsItemsInOrderWritten() throws BufferIOException { + public void itemsAreReadInTheOrderTheyAreWritten() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); + buffer.write(2); + assertThat(buffer.read()).isEqualTo(1); + assertThat(buffer.read()).isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("full buffer can't be written to") - public void fullBufferCantBeWrittenTo() throws BufferIOException { + public void fullBufferCanTBeWrittenTo() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); @@ -69,36 +74,45 @@ public void fullBufferCantBeWrittenTo() throws BufferIOException { @Disabled("Remove to run test") @Test @DisplayName("a read frees up capacity for another write") - public void readFreesUpSpaceForWrite() throws BufferIOException { + public void aReadFreesUpCapacityForAnotherWrite() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); + assertThat(buffer.read()).isEqualTo(1); + buffer.write(2); + assertThat(buffer.read()).isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("read position is maintained even across multiple writes") - public void maintainsReadPositionAcrossWrites() throws BufferIOException { + public void readPositionIsMaintainedEvenAcrossMultipleWrites() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(3); buffer.write(1); + buffer.write(2); + assertThat(buffer.read()).isEqualTo(1); + buffer.write(3); + assertThat(buffer.read()).isEqualTo(2); + assertThat(buffer.read()).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("items cleared out of buffer can't be read") - public void cantReadClearedItems() throws BufferIOException { + public void itemsClearedOutOfBufferCanTBeRead() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); + buffer.clear(); assertThatExceptionOfType(BufferIOException.class) @@ -109,12 +123,15 @@ public void cantReadClearedItems() throws BufferIOException { @Disabled("Remove to run test") @Test @DisplayName("clear frees up capacity for another write") - public void clearFreesUpCapacity() throws BufferIOException { + public void clearFreesUpCapacityForAnotherWrite() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); + buffer.clear(); + buffer.write(2); + assertThat(buffer.read()).isEqualTo(2); } @@ -125,7 +142,9 @@ public void clearDoesNothingOnEmptyBuffer() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.clear(); + buffer.write(1); + assertThat(buffer.read()).isEqualTo(1); } @@ -136,38 +155,53 @@ public void overwriteActsLikeWriteOnNonFullBuffer() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); + buffer.overwrite(2); + assertThat(buffer.read()).isEqualTo(1); + assertThat(buffer.read()).isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("overwrite replaces the oldest item on full buffer") - public void overwriteRemovesOldestElementOnFullBuffer() throws BufferIOException { + public void overwriteReplacesTheOldestItemOnFullBuffer() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); + buffer.write(2); + buffer.overwrite(3); + assertThat(buffer.read()).isEqualTo(2); + assertThat(buffer.read()).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("overwrite replaces the oldest item remaining in buffer following a read") - public void overwriteDoesntRemoveAnAlreadyReadElement() throws BufferIOException { + public void overwriteReplacesTheOldestItemRemainingInBufferFollowingARead() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(3); buffer.write(1); + buffer.write(2); + buffer.write(3); + assertThat(buffer.read()).isEqualTo(1); + buffer.write(4); + buffer.overwrite(5); + assertThat(buffer.read()).isEqualTo(3); + assertThat(buffer.read()).isEqualTo(4); + assertThat(buffer.read()).isEqualTo(5); } @@ -178,15 +212,22 @@ public void initialClearDoesNotAffectWrappingAround() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.clear(); + buffer.write(1); + buffer.write(2); + buffer.overwrite(3); + buffer.overwrite(4); + assertThat(buffer.read()).isEqualTo(3); + assertThat(buffer.read()).isEqualTo(4); assertThatExceptionOfType(BufferIOException.class) .isThrownBy(buffer::read) .withMessage("Tried to read from empty buffer"); } + } diff --git a/exercises/practice/collatz-conjecture/src/test/java/CollatzCalculatorTest.java b/exercises/practice/collatz-conjecture/src/test/java/CollatzCalculatorTest.java index c095ffdf6..63869dc27 100644 --- a/exercises/practice/collatz-conjecture/src/test/java/CollatzCalculatorTest.java +++ b/exercises/practice/collatz-conjecture/src/test/java/CollatzCalculatorTest.java @@ -7,50 +7,52 @@ public class CollatzCalculatorTest { - private CollatzCalculator collatzCalculator = new CollatzCalculator(); - @Test @DisplayName("zero steps for one") - public void testZeroStepsRequiredWhenStartingFrom1() { - assertThat(collatzCalculator.computeStepCount(1)).isEqualTo(0); + public void zeroStepsForOne() { + assertThat(new CollatzCalculator().computeStepCount(1)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("divide if even") - public void testCorrectNumberOfStepsWhenAllStepsAreDivisions() { - assertThat(collatzCalculator.computeStepCount(16)).isEqualTo(4); + public void divideIfEven() { + assertThat(new CollatzCalculator().computeStepCount(16)) + .isEqualTo(4); } @Disabled("Remove to run test") @Test @DisplayName("even and odd steps") - public void testCorrectNumberOfStepsWhenBothStepTypesAreNeeded() { - assertThat(collatzCalculator.computeStepCount(12)).isEqualTo(9); + public void evenAndOddSteps() { + assertThat(new CollatzCalculator().computeStepCount(12)) + .isEqualTo(9); } @Disabled("Remove to run test") @Test @DisplayName("large number of even and odd steps") - public void testAVeryLargeInput() { - assertThat(collatzCalculator.computeStepCount(1000000)).isEqualTo(152); + public void largeNumberOfEvenAndOddSteps() { + assertThat(new CollatzCalculator().computeStepCount(1000000)) + .isEqualTo(152); } @Disabled("Remove to run test") @Test @DisplayName("zero is an error") - public void testZeroIsConsideredInvalidInput() { + public void zeroIsAnError() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> collatzCalculator.computeStepCount(0)) + .isThrownBy(() -> new CollatzCalculator().computeStepCount(0)) .withMessage("Only positive integers are allowed"); } @Disabled("Remove to run test") @Test @DisplayName("negative value is an error") - public void testNegativeIntegerIsConsideredInvalidInput() { + public void negativeValueIsAnError() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> collatzCalculator.computeStepCount(-15)) + .isThrownBy(() -> new CollatzCalculator().computeStepCount(-15)) .withMessage("Only positive integers are allowed"); } diff --git a/exercises/practice/complex-numbers/src/test/java/ComplexNumberTest.java b/exercises/practice/complex-numbers/src/test/java/ComplexNumberTest.java index d9edc378a..1ec515246 100644 --- a/exercises/practice/complex-numbers/src/test/java/ComplexNumberTest.java +++ b/exercises/practice/complex-numbers/src/test/java/ComplexNumberTest.java @@ -7,8 +7,6 @@ public class ComplexNumberTest { - // Test helpers - private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-15; private void assertDoublesEqual(double d1, double d2, String numberPart) { @@ -22,29 +20,27 @@ private void assertComplexNumbersEqual(ComplexNumber c1, ComplexNumber c2) { assertDoublesEqual(c1.getImaginary(), c2.getImaginary(), "imaginary"); } - // Tests - @Test - @DisplayName("Real part of a purely real number") - public void testRealPartOfPurelyRealNumber() { + @DisplayName("Real part -> Real part of a purely real number") + public void realPartRealPartOfAPurelyRealNumber() { double expected = 1.0; - double actual = new ComplexNumber(1.0, 0).getReal(); + double actual = new ComplexNumber(1.0, 0.0).getReal(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Real part of a purely imaginary number") - public void testRealPartOfPurelyImaginaryNumber() { + @DisplayName("Real part -> Real part of a purely imaginary number") + public void realPartRealPartOfAPurelyImaginaryNumber() { double expected = 0.0; - double actual = new ComplexNumber(0, 1.0).getReal(); + double actual = new ComplexNumber(0.0, 1.0).getReal(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Real part of a number with real and imaginary part") - public void testRealPartOfNumberWithRealAndImaginaryParts() { + @DisplayName("Real part -> Real part of a number with real and imaginary part") + public void realPartRealPartOfANumberWithRealAndImaginaryPart() { double expected = 1.0; double actual = new ComplexNumber(1.0, 2.0).getReal(); assertDoublesEqual(expected, actual, "real"); @@ -52,26 +48,26 @@ public void testRealPartOfNumberWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Imaginary part of a purely real number") - public void testImaginaryPartOfPurelyRealNumber() { + @DisplayName("Imaginary part -> Imaginary part of a purely real number") + public void imaginaryPartImaginaryPartOfAPurelyRealNumber() { double expected = 0.0; - double actual = new ComplexNumber(1.0, 0).getImaginary(); + double actual = new ComplexNumber(1.0, 0.0).getImaginary(); assertDoublesEqual(expected, actual, "imaginary"); } @Disabled("Remove to run test") @Test - @DisplayName("Imaginary part of a purely imaginary number") - public void testImaginaryPartOfPurelyImaginaryNumber() { + @DisplayName("Imaginary part -> Imaginary part of a purely imaginary number") + public void imaginaryPartImaginaryPartOfAPurelyImaginaryNumber() { double expected = 1.0; - double actual = new ComplexNumber(0, 1.0).getImaginary(); + double actual = new ComplexNumber(0.0, 1.0).getImaginary(); assertDoublesEqual(expected, actual, "imaginary"); } @Disabled("Remove to run test") @Test - @DisplayName("Imaginary part of a number with real and imaginary part") - public void testImaginaryPartOfNumberWithRealAndImaginaryParts() { + @DisplayName("Imaginary part -> Imaginary part of a number with real and imaginary part") + public void imaginaryPartImaginaryPartOfANumberWithRealAndImaginaryPart() { double expected = 2.0; double actual = new ComplexNumber(1.0, 2.0).getImaginary(); assertDoublesEqual(expected, actual, "imaginary"); @@ -80,34 +76,34 @@ public void testImaginaryPartOfNumberWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test @DisplayName("Imaginary unit") - public void testImaginaryUnitExhibitsDefiningProperty() { - ComplexNumber expected = new ComplexNumber(-1.0, 0); - ComplexNumber actual = new ComplexNumber(0, 1.0).multiply(new ComplexNumber(0, 1.0)); + public void imaginaryUnit() { + ComplexNumber expected = new ComplexNumber(-1.0, 0.0); + ComplexNumber actual = new ComplexNumber(0.0, 1.0).multiply(new ComplexNumber(0.0, 1.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Add purely real numbers") - public void testAdditionWithPurelyRealNumbers() { - ComplexNumber expected = new ComplexNumber(3.0, 0); - ComplexNumber actual = new ComplexNumber(1.0, 0).add(new ComplexNumber(2.0, 0)); + @DisplayName("Arithmetic -> Addition -> Add purely real numbers") + public void arithmeticAdditionAddPurelyRealNumbers() { + ComplexNumber expected = new ComplexNumber(3.0, 0.0); + ComplexNumber actual = new ComplexNumber(1.0, 0.0).add(new ComplexNumber(2.0, 0.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Add purely imaginary numbers") - public void testAdditionWithPurelyImaginaryNumbers() { - ComplexNumber expected = new ComplexNumber(0, 3.0); - ComplexNumber actual = new ComplexNumber(0, 1.0).add(new ComplexNumber(0, 2.0)); + @DisplayName("Arithmetic -> Addition -> Add purely imaginary numbers") + public void arithmeticAdditionAddPurelyImaginaryNumbers() { + ComplexNumber expected = new ComplexNumber(0.0, 3.0); + ComplexNumber actual = new ComplexNumber(0.0, 1.0).add(new ComplexNumber(0.0, 2.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Add numbers with real and imaginary part") - public void testAdditionWithRealAndImaginaryParts() { + @DisplayName("Arithmetic -> Addition -> Add numbers with real and imaginary part") + public void arithmeticAdditionAddNumbersWithRealAndImaginaryPart() { ComplexNumber expected = new ComplexNumber(4.0, 6.0); ComplexNumber actual = new ComplexNumber(1.0, 2.0).add(new ComplexNumber(3.0, 4.0)); assertComplexNumbersEqual(expected, actual); @@ -115,8 +111,8 @@ public void testAdditionWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Subtract purely real numbers") - public void testSubtractionWithPurelyRealNumbers() { + @DisplayName("Arithmetic -> Subtraction -> Subtract purely real numbers") + public void arithmeticSubtractionSubtractPurelyRealNumbers() { ComplexNumber expected = new ComplexNumber(-1.0, 0.0); ComplexNumber actual = new ComplexNumber(1.0, 0.0).subtract(new ComplexNumber(2.0, 0.0)); assertComplexNumbersEqual(expected, actual); @@ -124,17 +120,17 @@ public void testSubtractionWithPurelyRealNumbers() { @Disabled("Remove to run test") @Test - @DisplayName("Subtract purely imaginary numbers") - public void testSubtractionWithPurelyImaginaryNumbers() { - ComplexNumber expected = new ComplexNumber(0, -1.0); - ComplexNumber actual = new ComplexNumber(0, 1.0).subtract(new ComplexNumber(0, 2.0)); + @DisplayName("Arithmetic -> Subtraction -> Subtract purely imaginary numbers") + public void arithmeticSubtractionSubtractPurelyImaginaryNumbers() { + ComplexNumber expected = new ComplexNumber(0.0, -1.0); + ComplexNumber actual = new ComplexNumber(0.0, 1.0).subtract(new ComplexNumber(0.0, 2.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Subtract numbers with real and imaginary part") - public void testSubtractionWithRealAndImaginaryParts() { + @DisplayName("Arithmetic -> Subtraction -> Subtract numbers with real and imaginary part") + public void arithmeticSubtractionSubtractNumbersWithRealAndImaginaryPart() { ComplexNumber expected = new ComplexNumber(-2.0, -2.0); ComplexNumber actual = new ComplexNumber(1.0, 2.0).subtract(new ComplexNumber(3.0, 4.0)); assertComplexNumbersEqual(expected, actual); @@ -142,26 +138,26 @@ public void testSubtractionWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Multiply purely real numbers") - public void testMultiplicationWithPurelyRealNumbers() { - ComplexNumber expected = new ComplexNumber(2.0, 0); - ComplexNumber actual = new ComplexNumber(1.0, 0).multiply(new ComplexNumber(2.0, 0)); + @DisplayName("Arithmetic -> Multiplication -> Multiply purely real numbers") + public void arithmeticMultiplicationMultiplyPurelyRealNumbers() { + ComplexNumber expected = new ComplexNumber(2.0, 0.0); + ComplexNumber actual = new ComplexNumber(1.0, 0.0).multiply(new ComplexNumber(2.0, 0.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply purely imaginary numbers") - public void testMultiplicationWithPurelyImaginaryNumbers() { - ComplexNumber expected = new ComplexNumber(-2.0, 0); - ComplexNumber actual = new ComplexNumber(0, 1.0).multiply(new ComplexNumber(0, 2.0)); + @DisplayName("Arithmetic -> Multiplication -> Multiply purely imaginary numbers") + public void arithmeticMultiplicationMultiplyPurelyImaginaryNumbers() { + ComplexNumber expected = new ComplexNumber(-2.0, 0.0); + ComplexNumber actual = new ComplexNumber(0.0, 1.0).multiply(new ComplexNumber(0.0, 2.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply numbers with real and imaginary part") - public void testMultiplicationWithRealAndImaginaryParts() { + @DisplayName("Arithmetic -> Multiplication -> Multiply numbers with real and imaginary part") + public void arithmeticMultiplicationMultiplyNumbersWithRealAndImaginaryPart() { ComplexNumber expected = new ComplexNumber(-5.0, 10.0); ComplexNumber actual = new ComplexNumber(1.0, 2.0).multiply(new ComplexNumber(3.0, 4.0)); assertComplexNumbersEqual(expected, actual); @@ -169,26 +165,26 @@ public void testMultiplicationWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Divide purely real numbers") - public void testDivisionWithPurelyRealNumbers() { - ComplexNumber expected = new ComplexNumber(0.5, 0); - ComplexNumber actual = new ComplexNumber(1.0, 0).divide(new ComplexNumber(2.0, 0)); + @DisplayName("Arithmetic -> Division -> Divide purely real numbers") + public void arithmeticDivisionDividePurelyRealNumbers() { + ComplexNumber expected = new ComplexNumber(0.5, 0.0); + ComplexNumber actual = new ComplexNumber(1.0, 0.0).divide(new ComplexNumber(2.0, 0.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Divide purely imaginary numbers") - public void testDivisionWithPurelyImaginaryNumbers() { - ComplexNumber expected = new ComplexNumber(0.5, 0); - ComplexNumber actual = new ComplexNumber(0, 1.0).divide(new ComplexNumber(0, 2.0)); + @DisplayName("Arithmetic -> Division -> Divide purely imaginary numbers") + public void arithmeticDivisionDividePurelyImaginaryNumbers() { + ComplexNumber expected = new ComplexNumber(0.5, 0.0); + ComplexNumber actual = new ComplexNumber(0.0, 1.0).divide(new ComplexNumber(0.0, 2.0)); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Divide numbers with real and imaginary part") - public void testDivisionWithRealAndImaginaryParts() { + @DisplayName("Arithmetic -> Division -> Divide numbers with real and imaginary part") + public void arithmeticDivisionDivideNumbersWithRealAndImaginaryPart() { ComplexNumber expected = new ComplexNumber(0.44, 0.08); ComplexNumber actual = new ComplexNumber(1.0, 2.0).divide(new ComplexNumber(3.0, 4.0)); assertComplexNumbersEqual(expected, actual); @@ -196,44 +192,46 @@ public void testDivisionWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a positive purely real number") - public void testAbsoluteValueOfPositivePurelyRealNumber() { + @DisplayName("Absolute value -> Absolute value of a positive purely real number") + public void absoluteValueAbsoluteValueOfAPositivePurelyRealNumber() { double expected = 5.0; - double actual = new ComplexNumber(5.0, 0).abs(); + double actual = new ComplexNumber(5.0, 0.0).abs(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a negative purely real number") - public void testAbsoluteValueOfNegativePurelyRealNumber() { + @DisplayName("Absolute value -> Absolute value of a negative purely real number") + public void absoluteValueAbsoluteValueOfANegativePurelyRealNumber() { double expected = 5.0; - double actual = new ComplexNumber(-5.0, 0).abs(); + double actual = new ComplexNumber(-5.0, 0.0).abs(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a purely imaginary number with positive imaginary part") - public void testAbsoluteValueOfPurelyImaginaryNumberWithPositiveImaginaryPart() { + @DisplayName("Absolute value -> Absolute value of a purely imaginary number with " + + "positive imaginary part") + public void absoluteValueAbsoluteValueOfAPurelyImaginaryNumberWithPositiveIma() { double expected = 5.0; - double actual = new ComplexNumber(0, 5.0).abs(); + double actual = new ComplexNumber(0.0, 5.0).abs(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a purely imaginary number with negative imaginary part") - public void testAbsoluteValueOfPurelyImaginaryNumberWithNegativeImaginaryPart() { + @DisplayName("Absolute value -> Absolute value of a purely imaginary number with " + + "negative imaginary part") + public void absoluteValueAbsoluteValueOfAPurelyImaginaryNumberWithNegativeIma() { double expected = 5.0; - double actual = new ComplexNumber(0, -5.0).abs(); + double actual = new ComplexNumber(0.0, -5.0).abs(); assertDoublesEqual(expected, actual, "real"); } @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a number with real and imaginary part") - public void testAbsoluteValueOfNumberWithRealAndImaginaryParts() { + @DisplayName("Absolute value -> Absolute value of a number with real and imaginary part") + public void absoluteValueAbsoluteValueOfANumberWithRealAndImaginaryPart() { double expected = 5.0; double actual = new ComplexNumber(3.0, 4.0).abs(); assertDoublesEqual(expected, actual, "real"); @@ -241,26 +239,26 @@ public void testAbsoluteValueOfNumberWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Conjugate a purely real number") - public void testConjugationOfPurelyRealNumber() { - ComplexNumber expected = new ComplexNumber(5.0, 0); - ComplexNumber actual = new ComplexNumber(5.0, 0).conjugate(); + @DisplayName("Complex conjugate -> Conjugate a purely real number") + public void complexConjugateConjugateAPurelyRealNumber() { + ComplexNumber expected = new ComplexNumber(5.0, 0.0); + ComplexNumber actual = new ComplexNumber(5.0, 0.0).conjugate(); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Conjugate a purely imaginary number") - public void testConjugationOfPurelyImaginaryNumber() { - ComplexNumber expected = new ComplexNumber(0, -5.0); - ComplexNumber actual = new ComplexNumber(0, 5.0).conjugate(); + @DisplayName("Complex conjugate -> Conjugate a purely imaginary number") + public void complexConjugateConjugateAPurelyImaginaryNumber() { + ComplexNumber expected = new ComplexNumber(0.0, -5.0); + ComplexNumber actual = new ComplexNumber(0.0, 5.0).conjugate(); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Conjugate a number with real and imaginary part") - public void testConjugationOfNumberWithRealAndImaginaryParts() { + @DisplayName("Complex conjugate -> Conjugate a number with real and imaginary part") + public void complexConjugateConjugateANumberWithRealAndImaginaryPart() { ComplexNumber expected = new ComplexNumber(1.0, -1.0); ComplexNumber actual = new ComplexNumber(1.0, 1.0).conjugate(); assertComplexNumbersEqual(expected, actual); @@ -268,36 +266,46 @@ public void testConjugationOfNumberWithRealAndImaginaryParts() { @Disabled("Remove to run test") @Test - @DisplayName("Euler's identity/formula") - public void testExponentialOfPurelyImaginaryNumber() { - ComplexNumber expected = new ComplexNumber(-1.0, 0); - ComplexNumber actual = new ComplexNumber(0, Math.PI).exponentialOf(); + @DisplayName("Complex exponential function -> Euler's identity/formula") + public void complexExponentialFunctionEulerSIdentityFormula() { + ComplexNumber expected = new ComplexNumber(-1.0, 0.0); + ComplexNumber actual = new ComplexNumber(0.0, Math.PI).exponentialOf(); + assertComplexNumbersEqual(expected, actual); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Complex exponential function -> Exponential of 0") + public void complexExponentialFunctionExponentialOf0() { + ComplexNumber expected = new ComplexNumber(1.0, 0.0); + ComplexNumber actual = new ComplexNumber(0.0, 0.0).exponentialOf(); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Exponential of 0") - public void testExponentialOfZero() { - ComplexNumber expected = new ComplexNumber(1.0, 0); - ComplexNumber actual = new ComplexNumber(0, 0).exponentialOf(); + @DisplayName("Complex exponential function -> Exponential of a purely real number") + public void complexExponentialFunctionExponentialOfAPurelyRealNumber() { + ComplexNumber expected = new ComplexNumber(Math.E, 0.0); + ComplexNumber actual = new ComplexNumber(1.0, 0.0).exponentialOf(); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Exponential of a purely real number") - public void testExponentialOfPurelyRealNumber() { - ComplexNumber expected = new ComplexNumber(Math.E, 0); - ComplexNumber actual = new ComplexNumber(1.0, 0).exponentialOf(); + @DisplayName("Complex exponential function -> Exponential of a number with real and imaginary part") + public void complexExponentialFunctionExponentialOfANumberWithRealAndImaginar() { + ComplexNumber expected = new ComplexNumber(-2.0, 0.0); + ComplexNumber actual = new ComplexNumber(Math.log(2.0), Math.PI).exponentialOf(); assertComplexNumbersEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Exponential resulting in a number with real and imaginary part") - public void testExponentialOfNumberWithRealAndImaginaryParts() { - ComplexNumber expected = new ComplexNumber(1, 1); + @DisplayName("Complex exponential function -> Exponential resulting in a number with " + + "real and imaginary part") + public void complexExponentialFunctionExponentialResultingInANumberWithRealAn() { + ComplexNumber expected = new ComplexNumber(1.0, 1.0); ComplexNumber actual = new ComplexNumber(Math.log(2.0) / 2, Math.PI / 4).exponentialOf(); assertComplexNumbersEqual(expected, actual); } diff --git a/exercises/practice/connect/src/test/java/ConnectTest.java b/exercises/practice/connect/src/test/java/ConnectTest.java index ae32c9920..ed84a75ab 100644 --- a/exercises/practice/connect/src/test/java/ConnectTest.java +++ b/exercises/practice/connect/src/test/java/ConnectTest.java @@ -9,250 +9,124 @@ public class ConnectTest { @Test @DisplayName("an empty board has no winner") public void anEmptyBoardHasNoWinner() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ ". . . . .", " . . . . .", " . . . . .", " . . . . .", " . . . . ." }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.NONE); + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.NONE); } @Disabled("Remove to run test") @Test @DisplayName("X can win on a 1x1 board") public void xCanWinOnA1x1Board() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "X" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_X); } @Disabled("Remove to run test") @Test @DisplayName("O can win on a 1x1 board") public void oCanWinOnA1x1Board() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "O" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_O); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_O); } @Disabled("Remove to run test") @Test @DisplayName("only edges does not make a winner") public void onlyEdgesDoesNotMakeAWinner() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "O O O X", " X . . X", " X . . X", " X O O O" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.NONE); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.NONE); } @Disabled("Remove to run test") @Test @DisplayName("illegal diagonal does not make a winner") public void illegalDiagonalDoesNotMakeAWinner() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "X O . .", " O X X X", " O X O .", " . O X .", " X X O O" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.NONE); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.NONE); } @Disabled("Remove to run test") @Test @DisplayName("nobody wins crossing adjacent angles") public void nobodyWinsCrossingAdjacentAngles() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "X . . .", " . X O .", " O . X O", " . O . X", " . . O ." }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.NONE); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.NONE); } @Disabled("Remove to run test") @Test @DisplayName("X wins crossing from left to right") public void xWinsCrossingFromLeftToRight() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ ". O . .", " O X X X", " O X O .", " X X O X", " . O X ." }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - - } - - @Disabled("Remove to run test") - @Test - @DisplayName("X wins with left-hand dead end fork") - public void xWinsWithLeftHandDeadEndFork() { - - //GIVEN - var board = new String[]{ - ". . X .", - " X X . .", - " . X X X", - " O O O O" - }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - - } - - @Disabled("Remove to run test") - @Test - @DisplayName("X wins with right-hand dead end fork") - public void xWinsWithRightHandDeadEndFork() { - - //GIVEN - var board = new String[]{ - ". . X X", - " X X . .", - " . X X .", - " O O O O" - }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_X); } @Disabled("Remove to run test") @Test @DisplayName("O wins crossing from top to bottom") public void oWinsCrossingFromTopToBottom() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ ". O . .", " O X X X", " O O O .", " X X O X", " . O X ." }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_O); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_O); } @Disabled("Remove to run test") @Test @DisplayName("X wins using a convoluted path") - public void xWinsUsingConvolutedPath() { - - //GIVEN - var board = new String[]{ + public void xWinsUsingAConvolutedPath() { + String[] board = new String[]{ ". X X . .", " X . X . X", " . X . X .", " . X X . .", " O O O O O" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_X); } @Disabled("Remove to run test") @Test @DisplayName("X wins using a spiral path") public void xWinsUsingASpiralPath() { - - //GIVEN - var board = new String[]{ + String[] board = new String[]{ "O X X X X X X X X", " O X O O O O O O O", " O X O X X X X X O", @@ -263,13 +137,7 @@ public void xWinsUsingASpiralPath() { " O O O O O O O X O", " X X X X X X X X O" }; - Connect cut = new Connect(board); - - //WHEN - var winner = cut.computeWinner(); - - //THEN - assertThat(winner).isEqualTo(Winner.PLAYER_X); - + assertThat(new Connect(board).computeWinner()).isEqualTo(Winner.PLAYER_X); } + } diff --git a/exercises/practice/crypto-square/src/test/java/CryptoSquareTest.java b/exercises/practice/crypto-square/src/test/java/CryptoSquareTest.java index 9b9225487..61eae29e7 100644 --- a/exercises/practice/crypto-square/src/test/java/CryptoSquareTest.java +++ b/exercises/practice/crypto-square/src/test/java/CryptoSquareTest.java @@ -8,81 +8,57 @@ public class CryptoSquareTest { @Test @DisplayName("empty plaintext results in an empty ciphertext") - public void emptyPlaintextResultsInEmptyCiphertext() { + public void emptyPlaintextResultsInAnEmptyCiphertext() { CryptoSquare cryptoSquare = new CryptoSquare(""); - String expectedOutput = ""; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("normalization results in empty plaintext") - public void normalizationResultsInEmptyCiphertext() { + public void normalizationResultsInEmptyPlaintext() { CryptoSquare cryptoSquare = new CryptoSquare("... --- ..."); - String expectedOutput = ""; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("Lowercase") - public void lettersAreLowerCasedDuringEncryption() { + public void lowercase() { CryptoSquare cryptoSquare = new CryptoSquare("A"); - String expectedOutput = "a"; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo("a"); } @Disabled("Remove to run test") @Test @DisplayName("Remove spaces") - public void spacesAreRemovedDuringEncryption() { - CryptoSquare cryptoSquare = new CryptoSquare(" b "); - String expectedOutput = "b"; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + public void removeSpaces() { + CryptoSquare cryptoSquare = new CryptoSquare(" b "); + assertThat(cryptoSquare.getCiphertext()).isEqualTo("b"); } @Disabled("Remove to run test") @Test @DisplayName("Remove punctuation") - public void punctuationIsRemovedDuringEncryption() { + public void removePunctuation() { CryptoSquare cryptoSquare = new CryptoSquare("@1,%!"); - String expectedOutput = "1"; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo("1"); } @Disabled("Remove to run test") @Test @DisplayName("9 character plaintext results in 3 chunks of 3 characters") - public void nineCharacterPlaintextResultsInThreeChunksOfThreeCharacters() { + public void test9CharacterPlaintextResultsIn3ChunksOf3Characters() { CryptoSquare cryptoSquare = new CryptoSquare("This is fun!"); - String expectedOutput = "tsf hiu isn"; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo("tsf hiu isn"); } @Disabled("Remove to run test") @Test @DisplayName("8 character plaintext results in 3 chunks, the last one with a trailing space") - public void eightCharacterPlaintextResultsInThreeChunksWithATrailingSpace() { + public void test8CharacterPlaintextResultsIn3ChunksTheLastOneWithATrailingSpa() { CryptoSquare cryptoSquare = new CryptoSquare("Chill out."); - String expectedOutput = "clu hlt io "; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); + assertThat(cryptoSquare.getCiphertext()).isEqualTo("clu hlt io "); } - @Disabled("Remove to run test") - @Test - @DisplayName("54 character plaintext results in 8 chunks, the last two with trailing spaces") - public void fiftyFourCharacterPlaintextResultsInEightChunksWithTrailingSpaces() { - CryptoSquare cryptoSquare = new CryptoSquare("If man was meant to stay on the ground, god would have " + - "given us roots."); - String expectedOutput = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau "; - - assertThat(cryptoSquare.getCiphertext()).isEqualTo(expectedOutput); - } } diff --git a/exercises/practice/custom-set/src/test/java/CustomSetTest.java b/exercises/practice/custom-set/src/test/java/CustomSetTest.java index 1032ecd50..e72491d3b 100644 --- a/exercises/practice/custom-set/src/test/java/CustomSetTest.java +++ b/exercises/practice/custom-set/src/test/java/CustomSetTest.java @@ -2,424 +2,425 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class CustomSetTest { @Test - @DisplayName("Returns true if the set contains no elements") - public void setsWithNoElementsAreEmpty() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); + @DisplayName("Returns true if the set contains no elements -> sets with no elements are empty") + public void returnsTrueIfTheSetContainsNoElementsSetsWithNoElementsAreEmpty() { + CustomSet customSet = new CustomSet<>(List.of()); assertThat(customSet.isEmpty()).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("sets with elements are not empty") - public void setsWithElementsAreNotEmpty() { - CustomSet customSet = new CustomSet<>(Collections.singletonList('1')); + @DisplayName("Returns true if the set contains no elements -> sets with elements are not empty") + public void returnsTrueIfTheSetContainsNoElementsSetsWithElementsAreNotEmpty() { + CustomSet customSet = new CustomSet<>(List.of(1)); assertThat(customSet.isEmpty()).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("nothing is contained in an empty set") - public void nothingIsContainedInAnEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.contains("1")).isFalse(); + @DisplayName("Sets can report if they contain an element -> nothing is contained in an empty set") + public void setsCanReportIfTheyContainAnElementNothingIsContainedInAnEmptySet() { + CustomSet customSet = new CustomSet<>(List.of()); + assertThat(customSet.contains(1)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("when the element is in the set") - public void whenTheElementIsInTheSet() { - CustomSet customSet = new CustomSet<>(Arrays.asList(1, 2, 3)); + @DisplayName("Sets can report if they contain an element -> when the element is in the set") + public void setsCanReportIfTheyContainAnElementWhenTheElementIsInTheSet() { + CustomSet customSet = new CustomSet<>(List.of(1, 2, 3)); assertThat(customSet.contains(1)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("when the element is not in the set") - public void whenTheElementIsNotInTheSet() { - CustomSet customSet = new CustomSet<>(Arrays.asList('1', '2', '3')); - assertThat(customSet.contains('4')).isFalse(); + @DisplayName("Sets can report if they contain an element -> when the element is not in the set") + public void setsCanReportIfTheyContainAnElementWhenTheElementIsNotInTheSet() { + CustomSet customSet = new CustomSet<>(List.of(1, 2, 3)); + assertThat(customSet.contains(4)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("empty set is a subset of another empty set") - public void emptySetIsASubsetOfAnotherEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.isSubset(secondCustomSet)).isTrue(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> empty set is a subset of another empty set") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetEmptySetI() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet2.isSubset(customSet1)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("empty set is a subset of non-empty set") - public void emptySetIsASubsetOfNonEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.singletonList(1)); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.isSubset(secondCustomSet)).isTrue(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> empty set is a subset of non-empty set") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetEmptySetI2() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(1)); + assertThat(customSet2.isSubset(customSet1)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty set is not a subset of empty set") - public void nonEmptySetIsNotASubsetOfEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Collections.singletonList('1')); - assertThat(customSet.isSubset(secondCustomSet)).isFalse(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> non-empty set is not a subset of empty set") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetNonEmptyS() { + CustomSet customSet1 = new CustomSet<>(List.of(1)); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet2.isSubset(customSet1)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("set is a subset of set with exact same elements") - public void setIsASubsetOfSetWithExactSameElements() { - CustomSet customSet = new CustomSet<>(Arrays.asList("1", "2", "3")); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("1", "2", "3")); - assertThat(customSet.isSubset(secondCustomSet)).isTrue(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> set is a subset of set with exact same elements") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetSetIsASub() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(1, 2, 3)); + assertThat(customSet2.isSubset(customSet1)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("set is a subset of larger set with same elements") - public void setIsASubsetOfLargerSetWithSameElements() { - CustomSet customSet = new CustomSet<>(Arrays.asList(4, 1, 2, 3)); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList(1, 2, 3)); - assertThat(customSet.isSubset(secondCustomSet)).isTrue(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> set is a subset of larger set with same elements") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetSetIsASub2() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(4, 1, 2, 3)); + assertThat(customSet2.isSubset(customSet1)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("set is not a subset of set that does not contain its elements") - public void setIsNotASubsetOfSetThatDoesNotContainItsElements() { - CustomSet customSet = new CustomSet<>(Arrays.asList('4', '1', '3')); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList('1', '2', '3')); - assertThat(customSet.isSubset(secondCustomSet)).isFalse(); + @DisplayName("A set is a subset if all of its elements are contained in the other " + + "set -> set is not a subset of set that does not contain its elements") + public void aSetIsASubsetIfAllOfItsElementsAreContainedInTheOtherSetSetIsNotA() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(4, 1, 3)); + assertThat(customSet2.isSubset(customSet1)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("the empty set is disjoint with itself") - public void theEmptySetIsDisjointWithItself() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.isDisjoint(secondCustomSet)).isTrue(); + @DisplayName("Sets are disjoint if they share no elements -> the empty set is disjoint with itself") + public void setsAreDisjointIfTheyShareNoElementsTheEmptySetIsDisjointWithItse() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet1.isDisjoint(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("empty set is disjoint with non-empty set") - public void emptySetIsDisjointWithNonEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Collections.singletonList(1)); - assertThat(customSet.isDisjoint(secondCustomSet)).isTrue(); + @DisplayName("Sets are disjoint if they share no elements -> empty set is disjoint " + + "with non-empty set") + public void setsAreDisjointIfTheyShareNoElementsEmptySetIsDisjointWithNonEmpt() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(1)); + assertThat(customSet1.isDisjoint(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty set is disjoint with empty set") - public void nonEmptySetIsDisjointWithEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.singletonList('1')); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.isDisjoint(secondCustomSet)).isTrue(); + @DisplayName("Sets are disjoint if they share no elements -> non-empty set is " + + "disjoint with empty set") + public void setsAreDisjointIfTheyShareNoElementsNonEmptySetIsDisjointWithEmpt() { + CustomSet customSet1 = new CustomSet<>(List.of(1)); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet1.isDisjoint(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("sets are not disjoint if they share an element") - public void setsAreNotDisjointIfTheyShareAnElement() { - CustomSet customSet = new CustomSet<>(Arrays.asList("1", "2")); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("2", "3")); - assertThat(customSet.isDisjoint(secondCustomSet)).isFalse(); + @DisplayName("Sets are disjoint if they share no elements -> sets are not disjoint " + + "if they share an element") + public void setsAreDisjointIfTheyShareNoElementsSetsAreNotDisjointIfTheyShare() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2)); + CustomSet customSet2 = new CustomSet<>(List.of(2, 3)); + assertThat(customSet1.isDisjoint(customSet2)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("sets are disjoint if they share no elements") - public void setsAreDisjointIfTheyShareNoElements() { - CustomSet customSet = new CustomSet<>(Arrays.asList(1, 2)); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList(3, 4)); - assertThat(customSet.isDisjoint(secondCustomSet)).isTrue(); + @DisplayName("Sets are disjoint if they share no elements -> sets are disjoint if " + + "they share no elements") + public void setsAreDisjointIfTheyShareNoElementsSetsAreDisjointIfTheyShareNoE() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2)); + CustomSet customSet2 = new CustomSet<>(List.of(3, 4)); + assertThat(customSet1.isDisjoint(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("empty sets are equal") - public void emptySetsAreEqual() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.equals(secondCustomSet)).isTrue(); + @DisplayName("Sets with the same elements are equal -> empty sets are equal") + public void setsWithTheSameElementsAreEqualEmptySetsAreEqual() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet1.equals(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("empty set is not equal to non-empty set") - public void emptySetIsNotEqualToNonEmptySet() { - CustomSet customSet = new CustomSet<>(Collections.emptyList()); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("1", "2", "3")); - assertThat(customSet.equals(secondCustomSet)).isFalse(); + @DisplayName("Sets with the same elements are equal -> empty set is not equal to non-empty set") + public void setsWithTheSameElementsAreEqualEmptySetIsNotEqualToNonEmptySet() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(1, 2, 3)); + assertThat(customSet1.equals(customSet2)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty set is not equal to empty set") - public void nonEmptySetIsNotEqualToEmptySet() { - CustomSet customSet = new CustomSet<>(Arrays.asList(1, 2, 3)); - CustomSet secondCustomSet = new CustomSet<>(Collections.emptyList()); - assertThat(customSet.equals(secondCustomSet)).isFalse(); + @DisplayName("Sets with the same elements are equal -> non-empty set is not equal to empty set") + public void setsWithTheSameElementsAreEqualNonEmptySetIsNotEqualToEmptySet() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of()); + assertThat(customSet1.equals(customSet2)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("sets with the same elements are equal") - public void setsWithTheSameElementsAreEqual() { - CustomSet customSet = new CustomSet<>(Arrays.asList('1', '2')); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList('2', '1')); - assertThat(customSet.equals(secondCustomSet)).isTrue(); + @DisplayName("Sets with the same elements are equal -> sets with the same elements are equal") + public void setsWithTheSameElementsAreEqualSetsWithTheSameElementsAreEqual() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2)); + CustomSet customSet2 = new CustomSet<>(List.of(2, 1)); + assertThat(customSet1.equals(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("sets with different elements are not equal") - public void setsWithDifferentElementsAreNotEqual() { - CustomSet customSet = new CustomSet<>(Arrays.asList("1", "2", "3")); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("1", "2", "4")); - assertThat(customSet.equals(secondCustomSet)).isFalse(); + @DisplayName("Sets with the same elements are equal -> sets with different elements are not equal") + public void setsWithTheSameElementsAreEqualSetsWithDifferentElementsAreNotEqu() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(1, 2, 4)); + assertThat(customSet1.equals(customSet2)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("set is not equal to larger set with same elements") - public void setIsNotEqualToLargerSetWithSameElements() { - CustomSet customSet = new CustomSet<>(Arrays.asList("1", "2", "3")); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("1", "2", "3", "4")); - assertThat(customSet.equals(secondCustomSet)).isFalse(); + @DisplayName("Sets with the same elements are equal -> set is not equal to larger " + + "set with same elements") + public void setsWithTheSameElementsAreEqualSetIsNotEqualToLargerSetWithSameEl() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(1, 2, 3, 4)); + assertThat(customSet1.equals(customSet2)).isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("set is equal to a set constructed from an array with duplicates") - public void secondSetWithDuplicatesIsEqualToFirstSet() { - CustomSet customSet = new CustomSet<>(Collections.singletonList("1")); - CustomSet secondCustomSet = new CustomSet<>(Arrays.asList("1", "1")); - assertThat(customSet.equals(secondCustomSet)).isTrue(); + @DisplayName("Sets with the same elements are equal -> set is equal to a set " + + "constructed from an array with duplicates") + public void setsWithTheSameElementsAreEqualSetIsEqualToASetConstructedFromAnA() { + CustomSet customSet1 = new CustomSet<>(List.of(1)); + CustomSet customSet2 = new CustomSet<>(List.of(1, 1)); + assertThat(customSet1.equals(customSet2)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("difference removes all duplicates in the first set") - public void firstSetWithDuplicatesIsEqualToSecondSet() { - CustomSet customSet = new CustomSet<>(Arrays.asList("1", "1")); - CustomSet secondCustomSet = new CustomSet<>(Collections.singletonList("1")); - assertThat(customSet.equals(secondCustomSet)).isTrue(); + @DisplayName("Unique elements can be added to a set -> add to empty set") + public void uniqueElementsCanBeAddedToASetAddToEmptySet() { + CustomSet customSet = new CustomSet<>(List.of()); + customSet.add(3); + CustomSet expected = new CustomSet<>(List.of(3)); + assertThat(customSet.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("add to empty set") - public void addToEmptySet() { - int element = 3; - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Collections.singletonList(element))); - CustomSet actual = new CustomSet<>(Collections.emptyList()); - - actual.add(element); - - assertThat(actual).isNotNull(); - assertThat(actual.equals(expected)).isTrue(); - assertThat(actual.isEmpty()).isFalse(); - + @DisplayName("Unique elements can be added to a set -> add to non-empty set") + public void uniqueElementsCanBeAddedToASetAddToNonEmptySet() { + CustomSet customSet = new CustomSet<>(List.of(1, 2, 4)); + customSet.add(3); + CustomSet expected = new CustomSet<>(List.of(1, 2, 3, 4)); + assertThat(customSet.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("add to non-empty set") - public void addToNonEmptySet() { - char element = '3'; - CustomSet expected = new CustomSet<>(Collections.unmodifiableList( - Arrays.asList('1', '2', '3', '4'))); - CustomSet actual = new CustomSet<>(Arrays.asList('1', '2', '4')); - - actual.add(element); - - assertThat(actual).isNotNull(); - assertThat(actual.equals(expected)).isTrue(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Unique elements can be added to a set -> adding an existing element " + + "does not change the set") + public void uniqueElementsCanBeAddedToASetAddingAnExistingElementDoesNotChang() { + CustomSet customSet = new CustomSet<>(List.of(1, 2, 3)); + customSet.add(3); + CustomSet expected = new CustomSet<>(List.of(1, 2, 3)); + assertThat(customSet.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("adding an existing element does not change the set") - public void addingAnExistingElementDoesNotChangeTheSet() { - String element = "3"; - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Arrays.asList("1", "2", "3"))); - CustomSet actual = new CustomSet<>(Arrays.asList("1", "2", "3")); - - actual.add(element); - - assertThat(actual).isNotNull(); + @DisplayName("Intersection returns a set of all shared elements -> intersection of " + + "two empty sets is an empty set") + public void intersectionReturnsASetOfAllSharedElementsIntersectionOfTwoEmptyS() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getIntersection(customSet2); + CustomSet expected = new CustomSet<>(List.of()); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("intersection of two empty sets is an empty set") - public void intersectionOfTwoEmptySetsIsAnEmptySet() { - CustomSet actual = new CustomSet(Collections.emptyList()) - .getIntersection(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Intersection returns a set of all shared elements -> intersection of " + + "an empty set and non-empty set is an empty set") + public void intersectionReturnsASetOfAllSharedElementsIntersectionOfAnEmptySe() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(3, 2, 5)); + CustomSet actual = customSet1.getIntersection(customSet2); + CustomSet expected = new CustomSet<>(List.of()); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("intersection of an empty set and non-empty set is an empty set") - public void intersectionOfAnEmptySetAndNonEmptySetIsAnEmptySet() { - CustomSet actual = new CustomSet(Collections.emptyList()) - .getIntersection(new CustomSet<>(Arrays.asList('3', '2', '5'))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Intersection returns a set of all shared elements -> intersection of a " + + "non-empty set and an empty set is an empty set") + public void intersectionReturnsASetOfAllSharedElementsIntersectionOfANonEmpty() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3, 4)); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getIntersection(customSet2); + CustomSet expected = new CustomSet<>(List.of()); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("intersection of a non-empty set and an empty set is an empty set") - public void intersectionOfANonEmptySetAndAnEmptySetIsAnEmptySet() { - CustomSet actual = new CustomSet<>(Arrays.asList("1", "2", "3", "4")) - .getIntersection(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); - + @DisplayName("Intersection returns a set of all shared elements -> intersection of " + + "two sets with no shared elements is an empty set") + public void intersectionReturnsASetOfAllSharedElementsIntersectionOfTwoSetsWi() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(4, 5, 6)); + CustomSet actual = customSet1.getIntersection(customSet2); + CustomSet expected = new CustomSet<>(List.of()); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("intersection of two sets with no shared elements is an empty set") - public void intersectionOfTwoSetsWithNoSharedElementsIsAnEmptySet() { - CustomSet actual = new CustomSet<>(Arrays.asList(1, 2, 3)) - .getIntersection(new CustomSet<>(Arrays.asList(4, 5, 6))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Intersection returns a set of all shared elements -> intersection of " + + "two sets with shared elements is a set of the shared elements") + public void intersectionReturnsASetOfAllSharedElementsIntersectionOfTwoSetsWi2() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3, 4)); + CustomSet customSet2 = new CustomSet<>(List.of(3, 2, 5)); + CustomSet actual = customSet1.getIntersection(customSet2); + CustomSet expected = new CustomSet<>(List.of(2, 3)); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("intersection of two sets with shared elements is a set of the shared elements") - public void intersectionOfTwoSetsWithSharedElementsIsASetOfTheSharedElements() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Arrays.asList('2', '3'))); - CustomSet actual = new CustomSet<>(Arrays.asList('1', '2', '3', '4')) - .getIntersection(new CustomSet<>(Arrays.asList('3', '2', '5'))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Difference (or Complement) of a set is a set of all elements that are " + + "only in the first set -> difference of two empty sets is an empty set") + public void differenceOrComplementOfASetIsASetOfAllElementsThatAreOnlyInTheFi() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getDifference(customSet2); + CustomSet expected = new CustomSet<>(List.of()); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("difference of two empty sets is an empty set") - public void differenceOfTwoEmptySetsIsAnEmptySet() { - CustomSet actual = new CustomSet(Collections.emptyList()) - .getDifference(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Difference (or Complement) of a set is a set of all elements that are " + + "only in the first set -> difference of empty set and non-empty set is " + + "an empty set") + public void differenceOrComplementOfASetIsASetOfAllElementsThatAreOnlyInTheFi2() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(3, 2, 5)); + CustomSet actual = customSet1.getDifference(customSet2); + CustomSet expected = new CustomSet<>(List.of()); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("difference of empty set and non-empty set is an empty set") - public void differenceOfAnEmptySetAndNonEmptySetIsAnEmptySet() { - CustomSet actual = new CustomSet(Collections.emptyList()) - .getDifference(new CustomSet<>(Arrays.asList(3, 2, 5))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Difference (or Complement) of a set is a set of all elements that are " + + "only in the first set -> difference of a non-empty set and an empty " + + "set is the non-empty set") + public void differenceOrComplementOfASetIsASetOfAllElementsThatAreOnlyInTheFi3() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 2, 3, 4)); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getDifference(customSet2); + CustomSet expected = new CustomSet<>(List.of(1, 2, 3, 4)); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("difference of a non-empty set and an empty set is the non-empty set") - public void differenceOfANonEmptySetAndAnEmptySetIsTheNonEmptySet() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList( - Arrays.asList('1', '2', '3', '4'))); - CustomSet actual = new CustomSet<>(Arrays.asList('1', '2', '3', '4')) - .getDifference(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Difference (or Complement) of a set is a set of all elements that are " + + "only in the first set -> difference of two non-empty sets is a set of " + + "elements that are only in the first set") + public void differenceOrComplementOfASetIsASetOfAllElementsThatAreOnlyInTheFi4() { + CustomSet customSet1 = new CustomSet<>(List.of(3, 2, 1)); + CustomSet customSet2 = new CustomSet<>(List.of(2, 4)); + CustomSet actual = customSet1.getDifference(customSet2); + CustomSet expected = new CustomSet<>(List.of(1, 3)); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("difference of two non-empty sets is a set of elements that are only in the first set") - public void differenceOfTwoNonEmptySetsIsASetOfElementsThatAreOnlyInTheFirstSet() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Arrays.asList("1", "3"))); - CustomSet actual = new CustomSet<>(Arrays.asList("3", "2", "1")) - .getDifference(new CustomSet<>(Arrays.asList("2", "4"))); - - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Difference (or Complement) of a set is a set of all elements that are " + + "only in the first set -> difference removes all duplicates in the " + + "first set") + public void differenceOrComplementOfASetIsASetOfAllElementsThatAreOnlyInTheFi5() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 1)); + CustomSet customSet2 = new CustomSet<>(List.of(1)); + CustomSet actual = customSet1.getDifference(customSet2); + CustomSet expected = new CustomSet<>(List.of()); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("union of empty sets is an empty set") - public void unionOfTwoEmptySetsIsAnEmptySet() { - CustomSet actual = new CustomSet(Collections.emptyList()) - .getUnion(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isTrue(); + @DisplayName("Union returns a set of all elements in either set -> union of empty " + + "sets is an empty set") + public void unionReturnsASetOfAllElementsInEitherSetUnionOfEmptySetsIsAnEmpty() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getUnion(customSet2); + CustomSet expected = new CustomSet<>(List.of()); + assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("union of an empty set and non-empty set is the non-empty set") - public void unionOfAnEmptySetAndNonEmptySetIsTheNonEmptySet() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Collections.singletonList('2'))); - CustomSet actual = new CustomSet(Collections.emptyList()) - .getUnion(new CustomSet<>(Collections.singletonList('2'))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Union returns a set of all elements in either set -> union of an empty " + + "set and non-empty set is the non-empty set") + public void unionReturnsASetOfAllElementsInEitherSetUnionOfAnEmptySetAndNonEm() { + CustomSet customSet1 = new CustomSet<>(List.of()); + CustomSet customSet2 = new CustomSet<>(List.of(2)); + CustomSet actual = customSet1.getUnion(customSet2); + CustomSet expected = new CustomSet<>(List.of(2)); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("union of a non-empty set and empty set is the non-empty set") - public void unionOfANonEmptySetAndAnEmptySetIsTheNonEmptySet() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Arrays.asList("1", "3"))); - CustomSet actual = new CustomSet<>(Arrays.asList("1", "3")) - .getUnion(new CustomSet<>(Collections.emptyList())); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Union returns a set of all elements in either set -> union of a " + + "non-empty set and empty set is the non-empty set") + public void unionReturnsASetOfAllElementsInEitherSetUnionOfANonEmptySetAndEmp() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 3)); + CustomSet customSet2 = new CustomSet<>(List.of()); + CustomSet actual = customSet1.getUnion(customSet2); + CustomSet expected = new CustomSet<>(List.of(1, 3)); assertThat(actual.equals(expected)).isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("union of non-empty sets contains all unique elements") - public void unionOfTwoNonEmptySetsContainsAllUniqueElements() { - CustomSet expected = new CustomSet<>(Collections.unmodifiableList(Arrays.asList(3, 2, 1))); - CustomSet actual = new CustomSet<>(Arrays.asList(1, 3)) - .getUnion(new CustomSet<>(Arrays.asList(2, 3))); - - assertThat(actual).isNotNull(); - assertThat(actual.isEmpty()).isFalse(); + @DisplayName("Union returns a set of all elements in either set -> union of " + + "non-empty sets contains all unique elements") + public void unionReturnsASetOfAllElementsInEitherSetUnionOfNonEmptySetsContai() { + CustomSet customSet1 = new CustomSet<>(List.of(1, 3)); + CustomSet customSet2 = new CustomSet<>(List.of(2, 3)); + CustomSet actual = customSet1.getUnion(customSet2); + CustomSet expected = new CustomSet<>(List.of(3, 2, 1)); assertThat(actual.equals(expected)).isTrue(); } diff --git a/exercises/practice/darts/src/test/java/DartsTest.java b/exercises/practice/darts/src/test/java/DartsTest.java index 45376bfe4..ba2789ee5 100644 --- a/exercises/practice/darts/src/test/java/DartsTest.java +++ b/exercises/practice/darts/src/test/java/DartsTest.java @@ -6,96 +6,107 @@ public class DartsTest { - Darts darts = new Darts(); @Test @DisplayName("Missed target") public void missedTarget() { - assertThat(darts.score(-9, 9)).isEqualTo(0); + assertThat(new Darts().score(-9, 9)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("On the outer circle") public void onTheOuterCircle() { - assertThat(darts.score(0, 10)).isEqualTo(1); + assertThat(new Darts().score(0, 10)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("On the middle circle") public void onTheMiddleCircle() { - assertThat(darts.score(-5, 0)).isEqualTo(5); + assertThat(new Darts().score(-5, 0)) + .isEqualTo(5); } @Disabled("Remove to run test") @Test @DisplayName("On the inner circle") public void onTheInnerCircle() { - assertThat(darts.score(0, -1)).isEqualTo(10); + assertThat(new Darts().score(0, -1)) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Exactly on center") - public void exactlyOnCentre() { - assertThat(darts.score(0, 0)).isEqualTo(10); + public void exactlyOnCenter() { + assertThat(new Darts().score(0, 0)) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Near the center") - public void nearTheCentre() { - assertThat(darts.score(-0.1, -0.1)).isEqualTo(10); + public void nearTheCenter() { + assertThat(new Darts().score(-0.1, -0.1)) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Just within the inner circle") public void justWithinTheInnerCircle() { - assertThat(darts.score(0.7, 0.7)).isEqualTo(10); + assertThat(new Darts().score(0.7, 0.7)) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Just outside the inner circle") public void justOutsideTheInnerCircle() { - assertThat(darts.score(0.8, -0.8)).isEqualTo(5); + assertThat(new Darts().score(0.8, -0.8)) + .isEqualTo(5); } @Disabled("Remove to run test") @Test @DisplayName("Just within the middle circle") public void justWithinTheMiddleCircle() { - assertThat(darts.score(-3.5, 3.5)).isEqualTo(5); + assertThat(new Darts().score(-3.5, 3.5)) + .isEqualTo(5); } @Disabled("Remove to run test") @Test @DisplayName("Just outside the middle circle") public void justOutsideTheMiddleCircle() { - assertThat(darts.score(-3.6, -3.6)).isEqualTo(1); + assertThat(new Darts().score(-3.6, -3.6)) + .isEqualTo(1); } - @Disabled("Remove to run test") @Test @DisplayName("Just within the outer circle") public void justWithinTheOuterCircle() { - assertThat(darts.score(-7.0, 7.0)).isEqualTo(1); + assertThat(new Darts().score(-7.0, 7.0)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("Just outside the outer circle") public void justOutsideTheOuterCircle() { - assertThat(darts.score(7.1, -7.1)).isEqualTo(0); + assertThat(new Darts().score(7.1, -7.1)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Asymmetric position between the inner and middle circles") public void asymmetricPositionBetweenTheInnerAndMiddleCircles() { - assertThat(darts.score(0.5, -4)).isEqualTo(5); + assertThat(new Darts().score(0.5, -4)) + .isEqualTo(5); } } diff --git a/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java b/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java index 6608faeac..c8c76f71d 100644 --- a/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java +++ b/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java @@ -1,122 +1,108 @@ -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class DiamondPrinterTest { +import static org.assertj.core.api.Assertions.assertThat; - private DiamondPrinter diamondPrinter; +public class DiamondPrinterTest { - @BeforeEach - public void setUp() { - diamondPrinter = new DiamondPrinter(); - } + private DiamondPrinter diamondPrinter = new DiamondPrinter(); @Test @DisplayName("Degenerate case with a single 'A' row") - public void testOneByOneDiamond() { + public void degenerateCaseWithASingleARow() { assertThat(diamondPrinter.printToList('A')) - .containsExactly("A"); + .containsExactly("A"); } @Disabled("Remove to run test") @Test @DisplayName("Degenerate case with no row containing 3 distinct groups of spaces") - public void testTwoByTwoDiamond() { + public void degenerateCaseWithNoRowContaining3DistinctGroupsOfSpaces() { assertThat(diamondPrinter.printToList('B')) - .containsExactly( - " A ", - "B B", - " A "); + .containsExactly(" A ", "B B", " A "); } @Disabled("Remove to run test") @Test @DisplayName("Smallest non-degenerate case with odd diamond side length") - public void testThreeByThreeDiamond() { + public void smallestNonDegenerateCaseWithOddDiamondSideLength() { assertThat(diamondPrinter.printToList('C')) - .containsExactly( - " A ", - " B B ", - "C C", - " B B ", - " A "); + .containsExactly(" A ", " B B ", "C C", " B B ", " A "); } @Disabled("Remove to run test") @Test @DisplayName("Smallest non-degenerate case with even diamond side length") - public void testFourByFourDiamond() { + public void smallestNonDegenerateCaseWithEvenDiamondSideLength() { assertThat(diamondPrinter.printToList('D')) - .containsExactly( - " A ", - " B B ", - " C C ", - "D D", - " C C ", - " B B ", - " A "); + .containsExactly( + " A ", + " B B ", + " C C ", + "D D", + " C C ", + " B B ", + " A "); } @Disabled("Remove to run test") @Test @DisplayName("Largest possible diamond") - public void testFullDiamond() { + public void largestPossibleDiamond() { assertThat(diamondPrinter.printToList('Z')) - .containsExactly( - " A ", - " B B ", - " C C ", - " D D ", - " E E ", - " F F ", - " G G ", - " H H ", - " I I ", - " J J ", - " K K ", - " L L ", - " M M ", - " N N ", - " O O ", - " P P ", - " Q Q ", - " R R ", - " S S ", - " T T ", - " U U ", - " V V ", - " W W ", - " X X ", - " Y Y ", - "Z Z", - " Y Y ", - " X X ", - " W W ", - " V V ", - " U U ", - " T T ", - " S S ", - " R R ", - " Q Q ", - " P P ", - " O O ", - " N N ", - " M M ", - " L L ", - " K K ", - " J J ", - " I I ", - " H H ", - " G G ", - " F F ", - " E E ", - " D D ", - " C C ", - " B B ", - " A "); + .containsExactly( + " A ", + " B B ", + " C C ", + " D D ", + " E E ", + " F F ", + " G G ", + " H H ", + " I I ", + " J J ", + " K K ", + " L L ", + " M M ", + " N N ", + " O O ", + " P P ", + " Q Q ", + " R R ", + " S S ", + " T T ", + " U U ", + " V V ", + " W W ", + " X X ", + " Y Y ", + "Z Z", + " Y Y ", + " X X ", + " W W ", + " V V ", + " U U ", + " T T ", + " S S ", + " R R ", + " Q Q ", + " P P ", + " O O ", + " N N ", + " M M ", + " L L ", + " K K ", + " J J ", + " I I ", + " H H ", + " G G ", + " F F ", + " E E ", + " D D ", + " C C ", + " B B ", + " A "); } } diff --git a/exercises/practice/difference-of-squares/src/test/java/DifferenceOfSquaresCalculatorTest.java b/exercises/practice/difference-of-squares/src/test/java/DifferenceOfSquaresCalculatorTest.java index 93d3af7a4..bd101a5c3 100644 --- a/exercises/practice/difference-of-squares/src/test/java/DifferenceOfSquaresCalculatorTest.java +++ b/exercises/practice/difference-of-squares/src/test/java/DifferenceOfSquaresCalculatorTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,91 +6,75 @@ public class DifferenceOfSquaresCalculatorTest { - private DifferenceOfSquaresCalculator calculator; - - @BeforeEach - public void setUp() { - calculator = new DifferenceOfSquaresCalculator(); - } - @Test - @DisplayName("square of sum 1") - public void testSquareOfSumUpToOne() { - int expected = 1; - int actual = calculator.computeSquareOfSumTo(1); - assertThat(actual).isEqualTo(expected); + @DisplayName("Square the sum of the numbers up to the given number -> square of sum 1") + public void squareTheSumOfTheNumbersUpToTheGivenNumberSquareOfSum1() { + assertThat(new DifferenceOfSquaresCalculator().computeSquareOfSumTo(1)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test - @DisplayName("square of sum 5") - public void testSquareOfSumUpToFive() { - int expected = 225; - int actual = calculator.computeSquareOfSumTo(5); - assertThat(actual).isEqualTo(expected); + @DisplayName("Square the sum of the numbers up to the given number -> square of sum 5") + public void squareTheSumOfTheNumbersUpToTheGivenNumberSquareOfSum5() { + assertThat(new DifferenceOfSquaresCalculator().computeSquareOfSumTo(5)) + .isEqualTo(225); } @Disabled("Remove to run test") @Test - @DisplayName("square of sum 100") - public void testSquareOfSumUpToHundred() { - int expected = 25502500; - int actual = calculator.computeSquareOfSumTo(100); - assertThat(actual).isEqualTo(expected); + @DisplayName("Square the sum of the numbers up to the given number -> square of sum 100") + public void squareTheSumOfTheNumbersUpToTheGivenNumberSquareOfSum100() { + assertThat(new DifferenceOfSquaresCalculator().computeSquareOfSumTo(100)) + .isEqualTo(25502500); } @Disabled("Remove to run test") @Test - @DisplayName("sum of squares 1") - public void testSumOfSquaresUpToOne() { - int expected = 1; - int actual = calculator.computeSumOfSquaresTo(1); - assertThat(actual).isEqualTo(expected); + @DisplayName("Sum the squares of the numbers up to the given number -> sum of squares 1") + public void sumTheSquaresOfTheNumbersUpToTheGivenNumberSumOfSquares1() { + assertThat(new DifferenceOfSquaresCalculator().computeSumOfSquaresTo(1)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test - @DisplayName("sum of squares 5") - public void testSumOfSquaresUpToFive() { - int expected = 55; - int actual = calculator.computeSumOfSquaresTo(5); - assertThat(actual).isEqualTo(expected); + @DisplayName("Sum the squares of the numbers up to the given number -> sum of squares 5") + public void sumTheSquaresOfTheNumbersUpToTheGivenNumberSumOfSquares5() { + assertThat(new DifferenceOfSquaresCalculator().computeSumOfSquaresTo(5)) + .isEqualTo(55); } @Disabled("Remove to run test") @Test - @DisplayName("sum of squares 100") - public void testSumOfSquaresUpToHundred() { - int expected = 338350; - int actual = calculator.computeSumOfSquaresTo(100); - assertThat(actual).isEqualTo(expected); + @DisplayName("Sum the squares of the numbers up to the given number -> sum of squares 100") + public void sumTheSquaresOfTheNumbersUpToTheGivenNumberSumOfSquares100() { + assertThat(new DifferenceOfSquaresCalculator().computeSumOfSquaresTo(100)) + .isEqualTo(338350); } @Disabled("Remove to run test") @Test - @DisplayName("difference of squares 1") - public void testDifferenceOfSquaresUpToOne() { - int expected = 0; - int actual = calculator.computeDifferenceOfSquares(1); - assertThat(actual).isEqualTo(expected); + @DisplayName("Subtract sum of squares from square of sums -> difference of squares 1") + public void subtractSumOfSquaresFromSquareOfSumsDifferenceOfSquares1() { + assertThat(new DifferenceOfSquaresCalculator().computeDifferenceOfSquares(1)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test - @DisplayName("difference of squares 5") - public void testDifferenceOfSquaresUpToFive() { - int expected = 170; - int actual = calculator.computeDifferenceOfSquares(5); - assertThat(actual).isEqualTo(expected); + @DisplayName("Subtract sum of squares from square of sums -> difference of squares 5") + public void subtractSumOfSquaresFromSquareOfSumsDifferenceOfSquares5() { + assertThat(new DifferenceOfSquaresCalculator().computeDifferenceOfSquares(5)) + .isEqualTo(170); } @Disabled("Remove to run test") @Test - @DisplayName("difference of squares 100") - public void testDifferenceOfSquaresUpToHundred() { - int expected = 25164150; - int actual = calculator.computeDifferenceOfSquares(100); - assertThat(actual).isEqualTo(expected); + @DisplayName("Subtract sum of squares from square of sums -> difference of squares 100") + public void subtractSumOfSquaresFromSquareOfSumsDifferenceOfSquares100() { + assertThat(new DifferenceOfSquaresCalculator().computeDifferenceOfSquares(100)) + .isEqualTo(25164150); } } diff --git a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java index c54ad52ac..4803529ab 100644 --- a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java +++ b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; public class DnDCharacterTest { @@ -11,187 +9,181 @@ public class DnDCharacterTest { private DnDCharacter dndCharacter = new DnDCharacter(); @Test - @DisplayName("ability modifier for score 3 is -4") - public void testAbilityModifierForScore3IsNegative4() { - assertThat(dndCharacter.modifier(3)).isEqualTo(-4); - } + @DisplayName("ability modifier -> ability modifier for score 3 is -4") + public void abilityModifierAbilityModifierForScore3Is4() { - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 4 is -3") - public void testAbilityModifierForScore4IsNegative3() { - assertThat(dndCharacter.modifier(4)).isEqualTo(-3); - } + assertThat(dndCharacter.modifier(3)) + .isEqualTo(-4); - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 5 is -3") - public void testAbilityModifierForScore5IsNegative3() { - assertThat(dndCharacter.modifier(5)).isEqualTo(-3); } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 6 is -2") - public void testAbilityModifierForScore6IsNegative2() { - assertThat(dndCharacter.modifier(6)).isEqualTo(-2); - } + @DisplayName("ability modifier -> ability modifier for score 4 is -3") + public void abilityModifierAbilityModifierForScore4Is3() { - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 7 is -2") - public void testAbilityModifierForScore7IsNegative2() { - assertThat(dndCharacter.modifier(7)).isEqualTo(-2); - } + assertThat(dndCharacter.modifier(4)) + .isEqualTo(-3); - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 8 is -1") - public void testAbilityModifierForScore8IsNegative1() { - assertThat(dndCharacter.modifier(8)).isEqualTo(-1); } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 9 is -1") - public void testAbilityModifierForScore9IsNegative1() { - assertThat(dndCharacter.modifier(9)).isEqualTo(-1); - } + @DisplayName("ability modifier -> ability modifier for score 5 is -3") + public void abilityModifierAbilityModifierForScore5Is3() { - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 10 is 0") - public void testAbilityModifierForScore10Is0() { - assertThat(dndCharacter.modifier(10)).isEqualTo(0); - } + assertThat(dndCharacter.modifier(5)) + .isEqualTo(-3); - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 11 is 0") - public void testAbilityModifierForScore11Is0() { - assertThat(dndCharacter.modifier(11)).isEqualTo(0); } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 12 is +1") - public void testAbilityModifierForScore12Is1() { - assertThat(dndCharacter.modifier(12)).isEqualTo(1); - } + @DisplayName("ability modifier -> ability modifier for score 6 is -2") + public void abilityModifierAbilityModifierForScore6Is2() { - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 13 is +1") - public void testAbilityModifierForScore13Is1() { - assertThat(dndCharacter.modifier(13)).isEqualTo(1); - } + assertThat(dndCharacter.modifier(6)) + .isEqualTo(-2); - @Disabled("Remove to run test") - @Test - @DisplayName("ability modifier for score 14 is +2") - public void testAbilityModifierForScore14Is2() { - assertThat(dndCharacter.modifier(14)).isEqualTo(2); } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 15 is +2") - public void testAbilityModifierForScore15Is2() { - assertThat(dndCharacter.modifier(15)).isEqualTo(2); + @DisplayName("ability modifier -> ability modifier for score 7 is -2") + public void abilityModifierAbilityModifierForScore7Is2() { + + assertThat(dndCharacter.modifier(7)) + .isEqualTo(-2); + } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 16 is +3") - public void testAbilityModifierForScore16Is3() { - assertThat(dndCharacter.modifier(16)).isEqualTo(3); + @DisplayName("ability modifier -> ability modifier for score 8 is -1") + public void abilityModifierAbilityModifierForScore8Is1() { + + assertThat(dndCharacter.modifier(8)) + .isEqualTo(-1); + } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 17 is +3") - public void testAbilityModifierForScore17Is3() { - assertThat(dndCharacter.modifier(17)).isEqualTo(3); + @DisplayName("ability modifier -> ability modifier for score 9 is -1") + public void abilityModifierAbilityModifierForScore9Is1() { + + assertThat(dndCharacter.modifier(9)) + .isEqualTo(-1); + } @Disabled("Remove to run test") @Test - @DisplayName("ability modifier for score 18 is +4") - public void testAbilityModifierForScore18Is4() { - assertThat(dndCharacter.modifier(18)).isEqualTo(4); + @DisplayName("ability modifier -> ability modifier for score 10 is 0") + public void abilityModifierAbilityModifierForScore10Is0() { + + assertThat(dndCharacter.modifier(10)) + .isEqualTo(0); + } @Disabled("Remove to run test") @Test - @DisplayName("Rolling uses 4 dice") - public void test4DiceWereUsedForRollingScores() { - assertThat(dndCharacter.rollDice().size()).isEqualTo(4); + @DisplayName("ability modifier -> ability modifier for score 11 is 0") + public void abilityModifierAbilityModifierForScore11Is0() { + + assertThat(dndCharacter.modifier(11)) + .isEqualTo(0); + } @Disabled("Remove to run test") @Test - @DisplayName("Dice values are between 1 and 6 inclusive") - public void testDiceValuesBetween1And6() { - assertThat(dndCharacter.rollDice()).allMatch(d -> d >= 1 && d <= 6); + @DisplayName("ability modifier -> ability modifier for score 12 is +1") + public void abilityModifierAbilityModifierForScore12Is1() { + + assertThat(dndCharacter.modifier(12)) + .isEqualTo(1); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability uses 3 largest numbers from scores in descending order") - public void testAbilityCalculationsUses3LargestNumbersFromScoresInDescendingOrder() { - assertThat(dndCharacter.ability(List.of(4, 3, 2, 1))).isEqualTo(9); + @DisplayName("ability modifier -> ability modifier for score 13 is +1") + public void abilityModifierAbilityModifierForScore13Is1() { + + assertThat(dndCharacter.modifier(13)) + .isEqualTo(1); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability uses 3 largest numbers from scores in ascending order") - public void testAbilityCalculationsUses3LargestNumbersFromFromScoresInAscendingOrder() { - assertThat(dndCharacter.ability(List.of(1, 2, 3, 4))).isEqualTo(9); + @DisplayName("ability modifier -> ability modifier for score 14 is +2") + public void abilityModifierAbilityModifierForScore14Is2() { + + assertThat(dndCharacter.modifier(14)) + .isEqualTo(2); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability uses 3 largest numbers from scores in random order") - public void testAbilityCalculationsUses3LargestNumbersFromScoresInRandomOrder() { - assertThat(dndCharacter.ability(List.of(2, 4, 3, 1))).isEqualTo(9); + @DisplayName("ability modifier -> ability modifier for score 15 is +2") + public void abilityModifierAbilityModifierForScore15Is2() { + + assertThat(dndCharacter.modifier(15)) + .isEqualTo(2); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability with all lowest equal numbers yields 3") - public void testAbilityCalculationsWithLowestEqualNumbers() { - assertThat(dndCharacter.ability(List.of(1, 1, 1, 1))).isEqualTo(3); + @DisplayName("ability modifier -> ability modifier for score 16 is +3") + public void abilityModifierAbilityModifierForScore16Is3() { + + assertThat(dndCharacter.modifier(16)) + .isEqualTo(3); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability with all highest equal numbers yields 18") - public void testAbilityCalculationsWithHighestEqualNumbers() { - assertThat(dndCharacter.ability(List.of(6, 6, 6, 6))).isEqualTo(18); + @DisplayName("ability modifier -> ability modifier for score 17 is +3") + public void abilityModifierAbilityModifierForScore17Is3() { + + assertThat(dndCharacter.modifier(17)) + .isEqualTo(3); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability calculation with two lowest numbers") - public void testAbilityCalculationsWithTwoLowestNumbers() { - assertThat(dndCharacter.ability(List.of(3, 5, 3, 4))).isEqualTo(12); + @DisplayName("ability modifier -> ability modifier for score 18 is +4") + public void abilityModifierAbilityModifierForScore18Is4() { + + assertThat(dndCharacter.modifier(18)) + .isEqualTo(4); + } @Disabled("Remove to run test") @Test - @DisplayName("Ability calculation does not mutate input scores") - public void testAbilityCalculationDoesNotChangeInputScores() { - List scores = List.of(1, 2, 3, 4); - dndCharacter.ability(scores); + @DisplayName("random ability is within range") + public void randomAbilityIsWithinRange() { + + for (int i = 0; i < 1000; i++) { + int score = dndCharacter.ability(dndCharacter.rollDice()); + assertThat(score).isGreaterThan(2).isLessThan(19); + } - assertThat(scores.size()).isEqualTo(4); - assertThat(scores).containsExactly(1, 2, 3, 4); } @Disabled("Remove to run test") @Test @DisplayName("random character is valid") - public void testRandomCharacterIsValid() { + public void randomCharacterIsValid() { + for (int i = 0; i < 1000; i++) { DnDCharacter character = new DnDCharacter(); assertThat(character.getStrength()).isGreaterThan(2).isLessThan(19); @@ -202,36 +194,22 @@ public void testRandomCharacterIsValid() { assertThat(character.getCharisma()).isGreaterThan(2).isLessThan(19); assertThat(character.getHitpoints()).isEqualTo(10 + character.modifier(character.getConstitution())); } + } @Disabled("Remove to run test") @Test @DisplayName("each ability is only calculated once") - public void testEachAbilityIsOnlyCalculatedOnce() { - assertThat(dndCharacter.getStrength()).isEqualTo(dndCharacter.getStrength()); - assertThat(dndCharacter.getDexterity()).isEqualTo(dndCharacter.getDexterity()); - assertThat(dndCharacter.getConstitution()).isEqualTo(dndCharacter.getConstitution()); - assertThat(dndCharacter.getIntelligence()).isEqualTo(dndCharacter.getIntelligence()); - assertThat(dndCharacter.getWisdom()).isEqualTo(dndCharacter.getWisdom()); - assertThat(dndCharacter.getCharisma()).isEqualTo(dndCharacter.getCharisma()); - } + public void eachAbilityIsOnlyCalculatedOnce() { + + DnDCharacter character = new DnDCharacter(); + assertThat(character.getStrength()).isEqualTo(character.getStrength()); + assertThat(character.getDexterity()).isEqualTo(character.getDexterity()); + assertThat(character.getConstitution()).isEqualTo(character.getConstitution()); + assertThat(character.getIntelligence()).isEqualTo(character.getIntelligence()); + assertThat(character.getWisdom()).isEqualTo(character.getWisdom()); + assertThat(character.getCharisma()).isEqualTo(character.getCharisma()); - @Disabled("Remove to run test") - @Test - @DisplayName("Each randomly created character should be unique in attributes") - public void testUniqueCharacterIsCreated() { - DnDCharacter uniqueDnDCharacter = new DnDCharacter(); - for (int i = 0; i < 1000; i++) { - DnDCharacter dnDCharacter = new DnDCharacter(); - boolean dnDCharactersHaveDifferentAttributes = - dnDCharacter.getStrength() != uniqueDnDCharacter.getStrength() - || dnDCharacter.getDexterity() != uniqueDnDCharacter.getDexterity() - || dnDCharacter.getConstitution() != uniqueDnDCharacter.getConstitution() - || dnDCharacter.getIntelligence() != uniqueDnDCharacter.getIntelligence() - || dnDCharacter.getWisdom() != uniqueDnDCharacter.getWisdom() - || dnDCharacter.getCharisma() != uniqueDnDCharacter.getCharisma() - || dnDCharacter.getHitpoints() != uniqueDnDCharacter.getHitpoints(); - assertThat(dnDCharactersHaveDifferentAttributes).isTrue(); - } } + } diff --git a/exercises/practice/dominoes/src/test/java/DominoesTest.java b/exercises/practice/dominoes/src/test/java/DominoesTest.java index d1570eb77..6c61295cf 100644 --- a/exercises/practice/dominoes/src/test/java/DominoesTest.java +++ b/exercises/practice/dominoes/src/test/java/DominoesTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -14,14 +12,13 @@ public class DominoesTest { @Test @DisplayName("empty input = empty output") - public void emtpyInputEmptyOutputTest() throws ChainNotFoundException { + public void emptyInputEmptyOutput() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - List dominoesList = new ArrayList<>(); + List dominoesList = List.of(); List chain = dominoes.formChain(dominoesList); + assertValidChain(dominoesList, chain); - assertThat(chain).withFailMessage("The output list should be empty.").hasSize(0); } @Disabled("Remove to run test") @@ -29,171 +26,201 @@ public void emtpyInputEmptyOutputTest() throws ChainNotFoundException { @DisplayName("singleton input = singleton output") public void singletonInputSingletonOutput() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 1)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of(new Domino(1, 1)); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("singleton that can't be chained") - public void singletonCantBeChainedTest() { + public void singletonThatCanTBeChained() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of(new Domino(1, 2)); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } @Disabled("Remove to run test") @Test @DisplayName("three elements") - public void threeElementsTest() throws ChainNotFoundException { + public void threeElements() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(3, 1), new Domino(2, 3)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(3, 1), + new Domino(2, 3) + ); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("can reverse dominoes") - public void canReverseDominoesTest() throws ChainNotFoundException { + public void canReverseDominoes() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(1, 3), new Domino(2, 3)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(1, 3), + new Domino(2, 3) + ); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("can't be chained") - public void cantBeChainedTest() { + public void canTBeChained() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(4, 1), new Domino(2, 3)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(4, 1), + new Domino(2, 3) + ); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } @Disabled("Remove to run test") @Test @DisplayName("disconnected - simple") - public void disconnectedSimpleTest() { + public void disconnectedSimple() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 1), new Domino(2, 2)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of(new Domino(1, 1), new Domino(2, 2)); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } @Disabled("Remove to run test") @Test @DisplayName("disconnected - double loop") - public void disconnectedDoubleLoopTest() { + public void disconnectedDoubleLoop() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 1), new Domino(3, 4), new Domino(4, 3)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(2, 1), + new Domino(3, 4), + new Domino(4, 3) + ); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } @Disabled("Remove to run test") @Test @DisplayName("disconnected - single isolated") - public void disconnectedSingleIsolatedTest() { + public void disconnectedSingleIsolated() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), new Domino(4, 4)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(2, 3), + new Domino(3, 1), + new Domino(4, 4) + ); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } @Disabled("Remove to run test") @Test @DisplayName("need backtrack") - public void needBacktrackTest() throws ChainNotFoundException { + public void needBacktrack() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), new Domino(2, 4), - new Domino(4, 2)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(2, 3), + new Domino(3, 1), + new Domino(2, 4), + new Domino(2, 4) + ); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("separate loops") - public void separateLoopsTest() throws ChainNotFoundException { + public void separateLoops() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), - new Domino(1, 1), new Domino(2, 2), new Domino(3, 3)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(2, 3), + new Domino(3, 1), + new Domino(1, 1), + new Domino(2, 2), + new Domino(3, 3) + ); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("nine elements") - public void nineElementsTest() throws ChainNotFoundException { + public void nineElements() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - Domino[] dominoesArray = {new Domino(1, 2), new Domino(5, 3), new Domino(3, 1), - new Domino(1, 2), new Domino(2, 4), new Domino(1, 6), - new Domino(2, 3), new Domino(3, 4), new Domino(5, 6)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(5, 3), + new Domino(3, 1), + new Domino(1, 2), + new Domino(2, 4), + new Domino(1, 6), + new Domino(2, 3), + new Domino(3, 4), + new Domino(5, 6) + ); List chain = dominoes.formChain(dominoesList); - assertValidChain(dominoesList, chain); + } @Disabled("Remove to run test") @Test @DisplayName("separate three-domino loops") - public void separateThreeDominoLoopsTest() { + public void separateThreeDominoLoops() throws ChainNotFoundException { Dominoes dominoes = new Dominoes(); - - Domino[] dominoesArray = {new Domino(1, 2), new Domino(2, 3), new Domino(3, 1), - new Domino(4, 5), new Domino(5, 6), new Domino (6, 4)}; - List dominoesList = Arrays.asList(dominoesArray); + List dominoesList = List.of( + new Domino(1, 2), + new Domino(2, 3), + new Domino(3, 1), + new Domino(4, 5), + new Domino(5, 6), + new Domino(6, 4) + ); assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); + } private void assertValidChain(List inputDominoes, List outputDominoes) { @@ -203,13 +230,16 @@ private void assertValidChain(List inputDominoes, List outputDom } private void assertEndDominoesMatch(List outputDominoes) { + if (outputDominoes.isEmpty()) { + return; + } int leftValueOfFirstDomino = outputDominoes.get(0).getLeft(); int rightValueOfLastDomino = outputDominoes.get(outputDominoes.size() - 1).getRight(); String errorMessage = "The left value of the first domino (" - + leftValueOfFirstDomino - + ") needs to match the right value of the last domino (" - + rightValueOfLastDomino - + ")."; + + leftValueOfFirstDomino + + ") needs to match the right value of the last domino (" + + rightValueOfLastDomino + + ")."; assertThat(leftValueOfFirstDomino).withFailMessage(errorMessage).isEqualTo(rightValueOfLastDomino); } @@ -224,9 +254,9 @@ private void assertSameDominoes(List inputDominoes, List outputD int inputFrequency = Collections.frequency(inputDominoes, domino); int outputFrequency = Collections.frequency(outputDominoes, domino); - String frequencyErrorMessage = "The frequency of domino (" + domino.getLeft() + ", " + - domino.getRight() + ")" + - " in the input is (" + inputFrequency + "), but (" + outputFrequency + ") in the output."; + String frequencyErrorMessage = "The frequency of domino (" + domino.getLeft() + ", " + + domino.getRight() + ")" + + " in the input is (" + inputFrequency + "), but (" + outputFrequency + ") in the output."; assertThat(inputFrequency).withFailMessage(frequencyErrorMessage).isEqualTo(outputFrequency); } @@ -234,17 +264,16 @@ private void assertSameDominoes(List inputDominoes, List outputD private void assertConsecutiveDominoes(List dominoes) { for (int i = 0; i < dominoes.size() - 1; i++) { - int rightValueOfIthDomino = dominoes.get(i).getRight(); int leftValueOfNextDomino = dominoes.get(i + 1).getLeft(); String errorMessage = "The right value of domino number " + i + " (" - + rightValueOfIthDomino - + ") needs to match the left value of domino number " + (i + 1) + " (" - + leftValueOfNextDomino - + ")."; + + rightValueOfIthDomino + + ") needs to match the left value of domino number " + (i + 1) + " (" + + leftValueOfNextDomino + + ")."; assertThat(dominoes.get(i).getRight()).withFailMessage(errorMessage) - .isEqualTo(dominoes.get(i + 1).getLeft()); + .isEqualTo(dominoes.get(i + 1).getLeft()); } } } diff --git a/exercises/practice/dot-dsl/src/test/java/GraphTest.java b/exercises/practice/dot-dsl/src/test/java/GraphTest.java index 93a6df747..71ed7d79e 100644 --- a/exercises/practice/dot-dsl/src/test/java/GraphTest.java +++ b/exercises/practice/dot-dsl/src/test/java/GraphTest.java @@ -1,17 +1,17 @@ -import static java.util.Collections.emptyMap; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Map; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.Collections; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + public class GraphTest { @Test @DisplayName("empty graph") - public void testEmptyGraph() { + public void emptyGraph() { Graph graph = new Graph(); assertThat(graph.getNodes()).isEmpty(); @@ -19,21 +19,21 @@ public void testEmptyGraph() { assertThat(graph.getAttributes()).isEmpty(); } + @Disabled("Remove to run test") @Test - @Disabled @DisplayName("graph with one node") - public void testGraphWithOneNode() { + public void graphWithOneNode() { Graph graph = new Graph().node("a"); - assertThat(graph.getNodes()).containsExactly(new Node("a", emptyMap())); + assertThat(graph.getNodes()).containsExactly(new Node("a", Collections.emptyMap())); assertThat(graph.getEdges()).isEmpty(); assertThat(graph.getAttributes()).isEmpty(); } + @Disabled("Remove to run test") @Test - @Disabled @DisplayName("graph with one node with attribute") - public void testGraphWithOneNodeWithAttribute() { + public void graphWithOneNodeWithAttribute() { Graph graph = new Graph().node("a", Map.of("color", "green")); assertThat(graph.getNodes()) @@ -42,10 +42,10 @@ public void testGraphWithOneNodeWithAttribute() { assertThat(graph.getAttributes()).isEmpty(); } + @Disabled("Remove to run test") @Test - @Disabled @DisplayName("graph with one edge") - public void testGraphWithOneEdge() { + public void graphWithOneEdge() { Graph graph = new Graph().edge("a", "b"); assertThat(graph.getNodes()).isEmpty(); @@ -54,22 +54,10 @@ public void testGraphWithOneEdge() { assertThat(graph.getAttributes()).isEmpty(); } + @Disabled("Remove to run test") @Test - @Disabled - @DisplayName("graph with one edge with attribute") - public void testGraphWithOneEdgeWithAttribute() { - Graph graph = new Graph().edge("a", "b", Map.of("color", "blue")); - - assertThat(graph.getNodes()).isEmpty(); - assertThat(graph.getEdges()) - .containsExactly(new Edge("a", "b", Map.of("color", "blue"))); - assertThat(graph.getAttributes()).isEmpty(); - } - - @Test - @Disabled @DisplayName("graph with one attribute") - public void testGraphWithOneAttribute() { + public void graphWithOneAttribute() { Graph graph = new Graph(Map.of("foo", "1")); assertThat(graph.getNodes()).isEmpty(); @@ -77,13 +65,12 @@ public void testGraphWithOneAttribute() { assertThat(graph.getAttributes()).containsEntry("foo", "1"); } + @Disabled("Remove to run test") @Test - @Disabled @DisplayName("graph with nodes, edges, and attributes") - public void testGraphWithNodesEdgesAndAttributes() { + public void graphWithNodesEdgesAndAttributes() { Graph graph = new Graph(Map.of("foo", "1", "title", "Testing Attrs", "bar", "true")) .node("a", Map.of("color", "green")) - .node("c") .node("b", Map.of("label", "Beta!")) .edge("b", "c") .edge("a", "b", Map.of("color", "blue")); @@ -91,23 +78,20 @@ public void testGraphWithNodesEdgesAndAttributes() { assertThat(graph.getNodes()) .containsExactlyInAnyOrder( new Node("a", Map.of("color", "green")), - new Node("c"), new Node("b", Map.of("label", "Beta!"))); - assertThat(graph.getEdges()) .containsExactlyInAnyOrder( - new Edge("a", "b", Map.of("color", "blue")), - new Edge("b", "c")); - + new Edge("b", "c"), + new Edge("a", "b", Map.of("color", "blue"))); assertThat(graph.getAttributes()) .containsExactlyInAnyOrderEntriesOf( Map.of("foo", "1", "title", "Testing Attrs", "bar", "true")); } + @Disabled("Remove to run test") @Test - @Disabled @DisplayName("multiple edges on one line") - public void testMultipleEdgesOnOneLine() { + public void multipleEdgesOnOneLine() { Graph graph = new Graph() .node("a") .node("b") @@ -117,19 +101,18 @@ public void testMultipleEdgesOnOneLine() { .edge("b", "c", Map.of("style", "dotted")) .edge("c", "d", Map.of("style", "dotted")); - assertThat(graph.getNodes()).containsExactlyInAnyOrder( - new Node("a"), - new Node("b"), - new Node("c"), - new Node("d") - ); - + assertThat(graph.getNodes()) + .containsExactlyInAnyOrder( + new Node("a"), + new Node("b"), + new Node("c"), + new Node("d")); assertThat(graph.getEdges()) - .containsExactlyInAnyOrder( - new Edge("a", "b", Map.of("style", "dotted")), - new Edge("b", "c", Map.of("style", "dotted")), - new Edge("c", "d", Map.of("style", "dotted")) - ); + .containsExactlyInAnyOrder( + new Edge("a", "b", Map.of("style", "dotted")), + new Edge("b", "c", Map.of("style", "dotted")), + new Edge("c", "d", Map.of("style", "dotted"))); assertThat(graph.getAttributes()).isEmpty(); } + } diff --git a/exercises/practice/eliuds-eggs/src/test/java/EliudsEggsTest.java b/exercises/practice/eliuds-eggs/src/test/java/EliudsEggsTest.java index fb193ee32..898c59bbe 100644 --- a/exercises/practice/eliuds-eggs/src/test/java/EliudsEggsTest.java +++ b/exercises/practice/eliuds-eggs/src/test/java/EliudsEggsTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class EliudsEggsTest { + @Test @DisplayName("0 eggs") public void test0Eggs() { @@ -35,4 +36,5 @@ public void test13Eggs() { assertThat(new EliudsEggs().eggCount(2000000000)) .isEqualTo(13); } + } diff --git a/exercises/practice/etl/src/test/java/EtlTest.java b/exercises/practice/etl/src/test/java/EtlTest.java index 4ef9292aa..250323ab5 100644 --- a/exercises/practice/etl/src/test/java/EtlTest.java +++ b/exercises/practice/etl/src/test/java/EtlTest.java @@ -2,137 +2,101 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; - public class EtlTest { + private final Etl etl = new Etl(); @Test @DisplayName("single letter") - public void testTransformOneValue() { - Map> old = new HashMap>() { - { - put(1, Arrays.asList("A")); - } - }; - old = Collections.unmodifiableMap(old); - - Map expected = new HashMap() { - { - put("a", 1); - } - }; - expected = Collections.unmodifiableMap(expected); + public void singleLetter() { + Map> legacy = Map.ofEntries(Map.entry(1, List.of("A"))); + Map expected = Map.ofEntries(Map.entry("a", 1)); - assertThat(etl.transform(old)).isEqualTo(expected); + assertThat(etl.transform(legacy)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("single score with multiple letters") - public void testTransformMoreValues() { - Map> old = new HashMap>() { - { - put(1, Arrays.asList("A", "E", "I", "O", "U")); - } - }; - old = Collections.unmodifiableMap(old); - - Map expected = new HashMap() { - { - put("a", 1); - put("e", 1); - put("i", 1); - put("o", 1); - put("u", 1); - } - }; - expected = Collections.unmodifiableMap(expected); - - assertThat(etl.transform(old)).isEqualTo(expected); + public void singleScoreWithMultipleLetters() { + Map> legacy = Map.ofEntries(Map.entry(1, List.of("A", "E", "I", "O", "U"))); + Map expected = Map.ofEntries( + Map.entry("a", 1), + Map.entry("e", 1), + Map.entry("i", 1), + Map.entry("o", 1), + Map.entry("u", 1) + ); + + assertThat(etl.transform(legacy)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("multiple scores with multiple letters") - public void testMoreKeys() { - Map> old = new HashMap>() { - { - put(1, Arrays.asList("A", "E")); - put(2, Arrays.asList("D", "G")); - } - }; - old = Collections.unmodifiableMap(old); - - Map expected = new HashMap() { - { - put("a", 1); - put("e", 1); - put("d", 2); - put("g", 2); - } - }; - expected = Collections.unmodifiableMap(expected); - - assertThat(etl.transform(old)).isEqualTo(expected); + public void multipleScoresWithMultipleLetters() { + Map> legacy = Map.ofEntries( + Map.entry(1, List.of("A", "E")), + Map.entry(2, List.of("D", "G")) + ); + Map expected = Map.ofEntries( + Map.entry("a", 1), + Map.entry("d", 2), + Map.entry("e", 1), + Map.entry("g", 2) + ); + + assertThat(etl.transform(legacy)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("multiple scores with differing numbers of letters") - public void testFullDataset() { - Map> old = new HashMap>() { - { - put(1, Arrays.asList("A", "E", "I", "O", "U", "L", "N", "R", "S", "T")); - put(2, Arrays.asList("D", "G")); - put(3, Arrays.asList("B", "C", "M", "P")); - put(4, Arrays.asList("F", "H", "V", "W", "Y")); - put(5, Arrays.asList("K")); - put(8, Arrays.asList("J", "X")); - put(10, Arrays.asList("Q", "Z")); - } - }; - old = Collections.unmodifiableMap(old); - - Map expected = new HashMap() { - { - put("a", 1); - put("b", 3); - put("c", 3); - put("d", 2); - put("e", 1); - put("f", 4); - put("g", 2); - put("h", 4); - put("i", 1); - put("j", 8); - put("k", 5); - put("l", 1); - put("m", 3); - put("n", 1); - put("o", 1); - put("p", 3); - put("q", 10); - put("r", 1); - put("s", 1); - put("t", 1); - put("u", 1); - put("v", 4); - put("w", 4); - put("x", 8); - put("y", 4); - put("z", 10); - } - }; - expected = Collections.unmodifiableMap(expected); - - assertThat(etl.transform(old)).isEqualTo(expected); + public void multipleScoresWithDifferingNumbersOfLetters() { + Map> legacy = Map.ofEntries( + Map.entry(1, List.of("A", "E", "I", "O", "U", "L", "N", "R", "S", "T")), + Map.entry(2, List.of("D", "G")), + Map.entry(3, List.of("B", "C", "M", "P")), + Map.entry(4, List.of("F", "H", "V", "W", "Y")), + Map.entry(5, List.of("K")), + Map.entry(8, List.of("J", "X")), + Map.entry(10, List.of("Q", "Z")) + ); + Map expected = Map.ofEntries( + Map.entry("a", 1), + Map.entry("b", 3), + Map.entry("c", 3), + Map.entry("d", 2), + Map.entry("e", 1), + Map.entry("f", 4), + Map.entry("g", 2), + Map.entry("h", 4), + Map.entry("i", 1), + Map.entry("j", 8), + Map.entry("k", 5), + Map.entry("l", 1), + Map.entry("m", 3), + Map.entry("n", 1), + Map.entry("o", 1), + Map.entry("p", 3), + Map.entry("q", 10), + Map.entry("r", 1), + Map.entry("s", 1), + Map.entry("t", 1), + Map.entry("u", 1), + Map.entry("v", 4), + Map.entry("w", 4), + Map.entry("x", 8), + Map.entry("y", 4), + Map.entry("z", 10) + ); + + assertThat(etl.transform(legacy)).isEqualTo(expected); } + } diff --git a/exercises/practice/flatten-array/src/test/java/FlattenerTest.java b/exercises/practice/flatten-array/src/test/java/FlattenerTest.java index 2a5fb4323..c6b7a7efa 100644 --- a/exercises/practice/flatten-array/src/test/java/FlattenerTest.java +++ b/exercises/practice/flatten-array/src/test/java/FlattenerTest.java @@ -1,132 +1,91 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; public class FlattenerTest { - private Flattener flattener; - - @BeforeEach - public void setUp() { - flattener = new Flattener(); - } - @Test @DisplayName("empty") - public void testEmpty() { - assertThat(flattener.flatten(emptyList())) - .isEmpty(); + public void empty() { + assertThat(new Flattener().flatten(List.of())) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("no nesting") - public void testFlatListIsPreserved() { - assertThat(flattener.flatten(asList(0, '1', "two"))) - .containsExactly(0, '1', "two"); + public void noNesting() { + assertThat(new Flattener().flatten(List.of(0, 1, 2))) + .isEqualTo(List.of(0, 1, 2)); } @Disabled("Remove to run test") @Test @DisplayName("flattens a nested array") - public void testNestedList() { - assertThat(flattener.flatten(singletonList(emptyList()))) - .isEmpty(); + public void flattensANestedArray() { + assertThat(new Flattener().flatten(List.of(List.of(List.of())))) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("flattens array with just integers present") - public void testASingleLevelOfNestingWithNoNulls() { - assertThat(flattener.flatten(asList(1, asList('2', 3, 4, 5, "six", "7"), 8))) - .containsExactly(1, '2', 3, 4, 5, "six", "7", 8); + public void flattensArrayWithJustIntegersPresent() { + assertThat(new Flattener().flatten(List.of(1, List.of(2, 3, 4, 5, 6, 7), 8))) + .isEqualTo(List.of(1, 2, 3, 4, 5, 6, 7, 8)); } @Disabled("Remove to run test") @Test @DisplayName("5 level nesting") - public void testFiveLevelsOfNestingWithNoNulls() { - assertThat(flattener.flatten( - asList(0, - '2', - asList(asList(2, "three"), - '8', - 100, - "four", - singletonList(singletonList(singletonList(50)))), "-2"))) - .containsExactly(0, '2', 2, "three", '8', 100, "four", 50, "-2"); + public void test5LevelNesting() { + assertThat(new Flattener().flatten(List.of( + 0, + 2, + List.of(List.of(2, 3), 8, 100, 4, List.of(List.of(List.of(50)))), + -2 + ))) + .isEqualTo(List.of( + 0, + 2, + 2, + 3, + 8, + 100, + 4, + 50, + -2 + )); } @Disabled("Remove to run test") @Test @DisplayName("6 level nesting") - public void testSixLevelsOfNestingWithNoNulls() { - assertThat(flattener.flatten( - asList("one", - asList('2', - singletonList(singletonList(3)), - asList('4', - singletonList(singletonList(5))), "six", 7), "8"))) - .containsExactly("one", '2', 3, '4', 5, "six", 7, "8"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("null values are omitted from the final result") - public void testNullValuesAreOmitted() { - assertThat(flattener.flatten(asList("1", "two", null))) - .containsExactly("1", "two"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("consecutive null values at the front of the list are omitted from the final result") - public void testConsecutiveNullValuesAtFrontOfListAreOmitted() { - assertThat(flattener.flatten(asList(null, null, 3))) - .containsExactly(3); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("consecutive null values in the middle of the list are omitted from the final result") - public void testConsecutiveNullValuesInMiddleOfListAreOmitted() { - assertThat(flattener.flatten(asList(1, null, null, "4"))) - .containsExactly(1, "4"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("6 level nest list with null values") - public void testSixLevelsOfNestingWithNulls() { - assertThat(flattener.flatten( - asList("0", + public void test6LevelNesting() { + assertThat(new Flattener().flatten(List.of( + 1, + List.of( 2, - asList(asList("two", '3'), - "8", - singletonList(singletonList("one hundred")), - null, - singletonList(singletonList(null))), - "negative two"))) - .containsExactly("0", 2, "two", '3', "8", "one hundred", "negative two"); + List.of(List.of(3)), + List.of(4, List.of(List.of(5))), + 6, + 7 + ), + 8 + ))) + .isEqualTo(List.of(1, 2, 3, 4, 5, 6, 7, 8)); } @Disabled("Remove to run test") @Test - @DisplayName("all values in nested list are null") - public void testNestedListsFullOfNullsOnly() { - assertThat(flattener.flatten( - asList(null, - singletonList(singletonList(singletonList(null))), - null, - null, - asList(asList(null, null), null), null))) - .isEmpty(); + @DisplayName("null values are omitted from the final result") + public void nullValuesAreOmittedFromTheFinalResult() { + assertThat(new Flattener().flatten(java.util.Arrays.asList(1, 2, null))) + .isEqualTo(List.of(1, 2)); } } diff --git a/exercises/practice/flower-field/src/test/java/FlowerFieldBoardTest.java b/exercises/practice/flower-field/src/test/java/FlowerFieldBoardTest.java index 58f995293..5bd6d33eb 100644 --- a/exercises/practice/flower-field/src/test/java/FlowerFieldBoardTest.java +++ b/exercises/practice/flower-field/src/test/java/FlowerFieldBoardTest.java @@ -2,7 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -11,259 +10,226 @@ public class FlowerFieldBoardTest { @Test @DisplayName("no rows") - public void testInputBoardWithNoRowsAndNoColumns() { - List inputBoard = Collections.emptyList(); - List expectedNumberedBoard = Collections.emptyList(); - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); + public void noRows() { + List inputBoard = List.of(); + List expected = List.of(); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("no columns") - public void testInputBoardWithOneRowAndNoColumns() { + public void noColumns() { List inputBoard = List.of(""); - List expectedNumberedBoard = List.of(""); - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); + List expected = List.of(""); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("no flowers") - public void testInputBoardWithNoFlowers() { + public void noFlowers() { List inputBoard = List.of( - " ", - " ", - " " - ); - - List expectedNumberedBoard = List.of( - " ", - " ", - " " - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + " ", + " ", + " " + ); + List expected = List.of( + " ", + " ", + " " + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("garden full of flowers") - public void testInputBoardWithOnlyFlowers() { + public void gardenFullOfFlowers() { List inputBoard = List.of( - "***", - "***", - "***" - ); - - List expectedNumberedBoard = List.of( - "***", - "***", - "***" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + "***", + "***", + "***" + ); + List expected = List.of( + "***", + "***", + "***" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("flower surrounded by spaces") - public void testInputBoardWithSingleFlowerAtCenter() { + public void flowerSurroundedBySpaces() { List inputBoard = List.of( - " ", - " * ", - " " - ); - - List expectedNumberedBoard = List.of( - "111", - "1*1", - "111" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + " ", + " * ", + " " + ); + List expected = List.of( + "111", + "1*1", + "111" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("space surrounded by flowers") - public void testInputBoardWithFlowersAroundPerimeter() { + public void spaceSurroundedByFlowers() { List inputBoard = List.of( - "***", - "* *", - "***" - ); - - List expectedNumberedBoard = List.of( - "***", - "*8*", - "***" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + "***", + "* *", + "***" + ); + List expected = List.of( + "***", + "*8*", + "***" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("horizontal line") - public void testInputBoardWithSingleRowAndTwoFlowers() { - List inputBoard = List.of( - " * * " - ); + public void horizontalLine() { + List inputBoard = List.of(" * * "); + List expected = List.of("1*2*1"); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); - List expectedNumberedBoard = List.of( - "1*2*1" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("horizontal line, flowers at edges") - public void testInputBoardWithSingleRowAndTwoFlowersAtEdges() { - List inputBoard = List.of( - "* *" - ); - - List expectedNumberedBoard = List.of( - "*1 1*" - ); + public void horizontalLineFlowersAtEdges() { + List inputBoard = List.of("* *"); + List expected = List.of("*1 1*"); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("vertical line") - public void testInputBoardWithSingleColumnAndTwoFlowers() { + public void verticalLine() { List inputBoard = List.of( - " ", - "*", - " ", - "*", - " " - ); - - List expectedNumberedBoard = List.of( - "1", - "*", - "2", - "*", - "1" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + " ", + "*", + " ", + "*", + " " + ); + List expected = List.of( + "1", + "*", + "2", + "*", + "1" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("vertical line, flowers at edges") - public void testInputBoardWithSingleColumnAndTwoFlowersAtEdges() { + public void verticalLineFlowersAtEdges() { List inputBoard = List.of( - "*", - " ", - " ", - " ", - "*" - ); - - List expectedNumberedBoard = List.of( - "*", - "1", - " ", - "1", - "*" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + "*", + " ", + " ", + " ", + "*" + ); + List expected = List.of( + "*", + "1", + " ", + "1", + "*" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("cross") - public void testInputBoardWithFlowersInCross() { + public void cross() { List inputBoard = List.of( - " * ", - " * ", - "*****", - " * ", - " * " - ); - - List expectedNumberedBoard = List.of( - " 2*2 ", - "25*52", - "*****", - "25*52", - " 2*2 " - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + " * ", + " * ", + "*****", + " * ", + " * " + ); + List expected = List.of( + " 2*2 ", + "25*52", + "*****", + "25*52", + " 2*2 " + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("large garden") - public void testLargeInputBoard() { + public void largeGarden() { List inputBoard = List.of( - " * * ", - " * ", - " * ", - " * *", - " * * ", - " " - ); - - List expectedNumberedBoard = List.of( - "1*22*1", - "12*322", - " 123*2", - "112*4*", - "1*22*2", - "111111" - ); - - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + " * * ", + " * ", + " * ", + " * *", + " * * ", + " " + ); + List expected = List.of( + "1*22*1", + "12*322", + " 123*2", + "112*4*", + "1*22*2", + "111111" + ); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("multiple adjacent flowers") - public void testMultipleAdjacentFlowers() { - List inputBoard = List.of( - " ** " - ); - - List expectedNumberedBoard = List.of( - "1**1" - ); + public void multipleAdjacentFlowers() { + List inputBoard = List.of(" ** "); + List expected = List.of("1**1"); + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); - List actualNumberedBoard = new FlowerFieldBoard(inputBoard).withNumbers(); - - assertThat(actualNumberedBoard).isEqualTo(expectedNumberedBoard); + assertThat(actual).isEqualTo(expected); } + } diff --git a/exercises/practice/food-chain/src/test/java/FoodChainTest.java b/exercises/practice/food-chain/src/test/java/FoodChainTest.java index 43e7a0746..d86c6de2b 100644 --- a/exercises/practice/food-chain/src/test/java/FoodChainTest.java +++ b/exercises/practice/food-chain/src/test/java/FoodChainTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,221 +5,309 @@ import static org.assertj.core.api.Assertions.assertThat; public class FoodChainTest { - private FoodChain foodChain; - @BeforeEach - public void setup() { - foodChain = new FoodChain(); - } + private FoodChain foodChain = new FoodChain(); @Test @DisplayName("fly") public void fly() { - int verse = 1; - String expected = "I know an old lady who swallowed a fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - assertThat(foodChain.verse(verse)).isEqualTo(expected); + assertThat(foodChain.verse(1)) + .isEqualTo("I know an old lady who swallowed a fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("spider") public void spider() { - int verse = 2; - String expected = "I know an old lady who swallowed a spider.\n" + - "It wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - assertThat(foodChain.verse(verse)).isEqualTo(expected); + assertThat(foodChain.verse(2)) + .isEqualTo("I know an old lady who swallowed a spider." + + "\n" + + "It wriggled and jiggled and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("bird") public void bird() { - int verse = 3; - String expected = "I know an old lady who swallowed a bird.\n" + - "How absurd to swallow a bird!\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verse(verse)).isEqualTo(expected); + + assertThat(foodChain.verse(3)) + .isEqualTo("I know an old lady who swallowed a bird." + + "\n" + + "How absurd to swallow a bird!" + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("cat") public void cat() { - int verse = 4; - String expected = "I know an old lady who swallowed a cat.\n" + - "Imagine that, to swallow a cat!\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verse(verse)).isEqualTo(expected); - } + assertThat(foodChain.verse(4)) + .isEqualTo("I know an old lady who swallowed a cat." + + "\n" + + "Imagine that, to swallow a cat!" + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("dog") public void dog() { - int verse = 5; - String expected = "I know an old lady who swallowed a dog.\n" + - "What a hog, to swallow a dog!\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verse(verse)).isEqualTo(expected); + + assertThat(foodChain.verse(5)) + .isEqualTo("I know an old lady who swallowed a dog." + + "\n" + + "What a hog, to swallow a dog!" + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("goat") public void goat() { - int verse = 6; - String expected = "I know an old lady who swallowed a goat.\n" + - "Just opened her throat and swallowed a goat!\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verse(verse)).isEqualTo(expected); + + assertThat(foodChain.verse(6)) + .isEqualTo("I know an old lady who swallowed a goat." + + "\n" + + "Just opened her throat and swallowed a goat!" + + "\n" + + "She swallowed the goat to catch the dog." + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("cow") public void cow() { - int verse = 7; - String expected = "I know an old lady who swallowed a cow.\n" + - "I don't know how she swallowed a cow!\n" + - "She swallowed the cow to catch the goat.\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verse(verse)).isEqualTo(expected); + + assertThat(foodChain.verse(7)) + .isEqualTo("I know an old lady who swallowed a cow." + + "\n" + + "I don't know how she swallowed a cow!" + + "\n" + + "She swallowed the cow to catch the goat." + + "\n" + + "She swallowed the goat to catch the dog." + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("horse") public void horse() { - int verse = 8; - String expected = "I know an old lady who swallowed a horse.\n" + - "She's dead, of course!"; - assertThat(foodChain.verse(verse)).isEqualTo(expected); - } + assertThat(foodChain.verse(8)) + .isEqualTo("I know an old lady who swallowed a horse." + + "\n" + + "She's dead, of course!"); + } + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("multiple verses") public void multipleVerses() { - int startVerse = 1; - int endVerse = 3; - String expected = "I know an old lady who swallowed a fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a spider.\n" + - "It wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a bird.\n" + - "How absurd to swallow a bird!\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die."; - - assertThat(foodChain.verses(startVerse, endVerse)).isEqualTo(expected); - } + assertThat(foodChain.verses(1, 3)) + .isEqualTo("I know an old lady who swallowed a fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a spider." + + "\n" + + "It wriggled and jiggled and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a bird." + + "\n" + + "How absurd to swallow a bird!" + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die."); + } + + @Disabled("Remove to run test") @Test - @Disabled("Remove to run test.") @DisplayName("full song") - public void wholeSong() { - int startVerse = 1; - int endVerse = 8; - String expected = "I know an old lady who swallowed a fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a spider.\n" + - "It wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a bird.\n" + - "How absurd to swallow a bird!\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a cat.\n" + - "Imagine that, to swallow a cat!\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a dog.\n" + - "What a hog, to swallow a dog!\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a goat.\n" + - "Just opened her throat and swallowed a goat!\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a cow.\n" + - "I don't know how she swallowed a cow!\n" + - "She swallowed the cow to catch the goat.\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and " + - "tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n" + - "\n" + - "I know an old lady who swallowed a horse.\n" + - "She's dead, of course!"; - - assertThat(foodChain.verses(startVerse, endVerse)).isEqualTo(expected); + public void fullSong() { + + assertThat(foodChain.verses(1, 8)) + .isEqualTo("I know an old lady who swallowed a fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a spider." + + "\n" + + "It wriggled and jiggled and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a bird." + + "\n" + + "How absurd to swallow a bird!" + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a cat." + + "\n" + + "Imagine that, to swallow a cat!" + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a dog." + + "\n" + + "What a hog, to swallow a dog!" + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a goat." + + "\n" + + "Just opened her throat and swallowed a goat!" + + "\n" + + "She swallowed the goat to catch the dog." + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a cow." + + "\n" + + "I don't know how she swallowed a cow!" + + "\n" + + "She swallowed the cow to catch the goat." + + "\n" + + "She swallowed the goat to catch the dog." + + "\n" + + "She swallowed the dog to catch the cat." + + "\n" + + "She swallowed the cat to catch the bird." + + "\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled " + + "and tickled inside her." + + "\n" + + "She swallowed the spider to catch the fly." + + "\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." + + "\n" + + "" + + "\n" + + "I know an old lady who swallowed a horse." + + "\n" + + "She's dead, of course!"); + } + } diff --git a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java index 9a7c23e01..dae1f1ada 100644 --- a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java +++ b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -14,455 +12,465 @@ public class ForthEvaluatorTest { private ForthEvaluator forthEvaluator = new ForthEvaluator(); @Test - @DisplayName("numbers just get pushed onto the stack") - public void testNumbersAreJustPushedOntoTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 4 5"))) + @DisplayName("parsing and numbers -> numbers just get pushed onto the stack") + public void parsingAndNumbersNumbersJustGetPushedOntoTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 4 5"))) .containsExactly(1, 2, 3, 4, 5); } @Disabled("Remove to run test") @Test - @DisplayName("pushes negative numbers onto the stack") - public void testNegativeNumbersArePushedOntoTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("-1 -2 -3 -4 -5"))) + @DisplayName("parsing and numbers -> pushes negative numbers onto the stack") + public void parsingAndNumbersPushesNegativeNumbersOntoTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("-1 -2 -3 -4 -5"))) .containsExactly(-1, -2, -3, -4, -5); } @Disabled("Remove to run test") @Test - @DisplayName("can add two numbers") - public void testTwoNumbersCanBeAdded() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 +"))) + @DisplayName("addition -> can add two numbers") + public void additionCanAddTwoNumbers() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 +"))) .containsExactly(3); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfAdditionAttemptedWithNothingOnTheStack() { + @DisplayName("addition -> errors if there is nothing on the stack") + public void additionErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("+"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("+"))) .withMessage("Addition requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfAdditionAttemptedWithOneNumberOnTheStack() { + @DisplayName("addition -> errors if there is only one value on the stack") + public void additionErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 +"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 +"))) .withMessage("Addition requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("more than two values on the stack") - public void testAdditionForMoreThanTwoValuesOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 +"))) + @DisplayName("addition -> more than two values on the stack") + public void additionMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 +"))) .containsExactly(1, 5); } @Disabled("Remove to run test") @Test - @DisplayName("can subtract two numbers") - public void testTwoNumbersCanBeSubtracted() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("3 4 -"))) + @DisplayName("subtraction -> can subtract two numbers") + public void subtractionCanSubtractTwoNumbers() { + assertThat(forthEvaluator.evaluateProgram(List.of("3 4 -"))) .containsExactly(-1); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfSubtractionAttemptedWithNothingOnTheStack() { + @DisplayName("subtraction -> errors if there is nothing on the stack") + public void subtractionErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("-"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("-"))) .withMessage("Subtraction requires that the stack contain at least 2 values"); - } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfSubtractionAttemptedWithOneNumberOnTheStack() { + @DisplayName("subtraction -> errors if there is only one value on the stack") + public void subtractionErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 -"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 -"))) .withMessage("Subtraction requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("more than two values on the stack") - public void testSubtractionForMoreThanTwoValuesOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 12 3 -"))) + @DisplayName("subtraction -> more than two values on the stack") + public void subtractionMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 12 3 -"))) .containsExactly(1, 9); } @Disabled("Remove to run test") @Test - @DisplayName("can multiply two numbers") - public void testTwoNumbersCanBeMultiplied() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("2 4 *"))).containsExactly(8); + @DisplayName("multiplication -> can multiply two numbers") + public void multiplicationCanMultiplyTwoNumbers() { + assertThat(forthEvaluator.evaluateProgram(List.of("2 4 *"))) + .containsExactly(8); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfMultiplicationAttemptedWithNothingOnTheStack() { + @DisplayName("multiplication -> errors if there is nothing on the stack") + public void multiplicationErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("*"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("*"))) .withMessage("Multiplication requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfMultiplicationAttemptedWithOneNumberOnTheStack() { + @DisplayName("multiplication -> errors if there is only one value on the stack") + public void multiplicationErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 *"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 *"))) .withMessage("Multiplication requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("more than two values on the stack") - public void testMultiplicationForMoreThanTwoValuesOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 *"))) + @DisplayName("multiplication -> more than two values on the stack") + public void multiplicationMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 *"))) .containsExactly(1, 6); } @Disabled("Remove to run test") @Test - @DisplayName("can divide two numbers") - public void testTwoNumbersCanBeDivided() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("12 3 /"))).containsExactly(4); + @DisplayName("division -> can divide two numbers") + public void divisionCanDivideTwoNumbers() { + assertThat(forthEvaluator.evaluateProgram(List.of("12 3 /"))) + .containsExactly(4); } @Disabled("Remove to run test") @Test - @DisplayName("performs integer division") - public void testThatIntegerDivisionIsUsed() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("8 3 /"))).containsExactly(2); + @DisplayName("division -> performs integer division") + public void divisionPerformsIntegerDivision() { + assertThat(forthEvaluator.evaluateProgram(List.of("8 3 /"))) + .containsExactly(2); } @Disabled("Remove to run test") @Test - @DisplayName("errors if dividing by zero") - public void testErrorIfDividingByZero() { + @DisplayName("division -> errors if dividing by zero") + public void divisionErrorsIfDividingByZero() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("4 0 /"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("4 0 /"))) .withMessage("Division by 0 is not allowed"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfDivisionAttemptedWithNothingOnTheStack() { + @DisplayName("division -> errors if there is nothing on the stack") + public void divisionErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("/"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("/"))) .withMessage("Division requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfDivisionAttemptedWithOneNumberOnTheStack() { + @DisplayName("division -> errors if there is only one value on the stack") + public void divisionErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 /"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 /"))) .withMessage("Division requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("more than two values on the stack") - public void testDivisionForMoreThanTwoValuesOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 12 3 /"))) + @DisplayName("division -> more than two values on the stack") + public void divisionMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 12 3 /"))) .containsExactly(1, 4); } @Disabled("Remove to run test") @Test - @DisplayName("addition and subtraction") - public void testCombinedAdditionAndSubtraction() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 + 4 -"))).containsExactly(-1); + @DisplayName("combined arithmetic -> addition and subtraction") + public void combinedArithmeticAdditionAndSubtraction() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 + 4 -"))) + .containsExactly(-1); } @Disabled("Remove to run test") @Test - @DisplayName("multiplication and division") - public void testCombinedMultiplicationAndDivision() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("2 4 * 3 /"))).containsExactly(2); + @DisplayName("combined arithmetic -> multiplication and division") + public void combinedArithmeticMultiplicationAndDivision() { + assertThat(forthEvaluator.evaluateProgram(List.of("2 4 * 3 /"))) + .containsExactly(2); } @Disabled("Remove to run test") @Test - @DisplayName("multiplication and addition") - public void testCombinedMultiplicationAndAddition() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 3 4 * +"))).containsExactly(13); + @DisplayName("combined arithmetic -> multiplication and addition") + public void combinedArithmeticMultiplicationAndAddition() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 3 4 * +"))) + .containsExactly(13); } @Disabled("Remove to run test") @Test - @DisplayName("addition and multiplication") - public void testCombinedAdditionAndMultiplication() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 3 4 + *"))).containsExactly(7); + @DisplayName("combined arithmetic -> addition and multiplication") + public void combinedArithmeticAdditionAndMultiplication() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 3 4 + *"))) + .containsExactly(7); } @Disabled("Remove to run test") @Test - @DisplayName("copies a value on the stack") - public void testDupCopiesAValueOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 dup"))).containsExactly(1, 1); + @DisplayName("dup -> copies a value on the stack") + public void dupCopiesAValueOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 dup"))) + .containsExactly(1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("copies the top value on the stack") - public void testDupCopiesTopValueOnTheStack() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 dup"))).containsExactly(1, 2, 2); + @DisplayName("dup -> copies the top value on the stack") + public void dupCopiesTheTopValueOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 dup"))) + .containsExactly(1, 2, 2); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfDuplicatingAttemptedWithNothingOnTheStack() { + @DisplayName("dup -> errors if there is nothing on the stack") + public void dupErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("dup"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("dup"))) .withMessage("Duplicating requires that the stack contain at least 1 value"); } @Disabled("Remove to run test") @Test - @DisplayName("removes the top value on the stack if it is the only one") - public void testDropRemovesTheTopValueOnTheStackIfItIsTheOnlyOne() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 drop"))).isEmpty(); + @DisplayName("drop -> removes the top value on the stack if it is the only one") + public void dropRemovesTheTopValueOnTheStackIfItIsTheOnlyOne() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 drop"))) + .containsExactly(); } @Disabled("Remove to run test") @Test - @DisplayName("removes the top value on the stack if it is not the only one") - public void testDropRemovesTheTopValueOnTheStackIfItIsNotTheOnlyOne() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 drop"))).containsExactly(1); + @DisplayName("drop -> removes the top value on the stack if it is not the only one") + public void dropRemovesTheTopValueOnTheStackIfItIsNotTheOnlyOne() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 drop"))) + .containsExactly(1); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfDroppingAttemptedWithNothingOnTheStack() { + @DisplayName("drop -> errors if there is nothing on the stack") + public void dropErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("drop"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("drop"))) .withMessage("Dropping requires that the stack contain at least 1 value"); } @Disabled("Remove to run test") @Test - @DisplayName("swaps the top two values on the stack if they are the only ones") - public void testSwapSwapsTheTopTwosValueOnTheStackIfTheyAreTheOnlyOnes() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 swap"))).containsExactly(2, 1); + @DisplayName("swap -> swaps the top two values on the stack if they are the only ones") + public void swapSwapsTheTopTwoValuesOnTheStackIfTheyAreTheOnlyOnes() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 swap"))) + .containsExactly(2, 1); } @Disabled("Remove to run test") @Test - @DisplayName("swaps the top two values on the stack if they are not the only ones") - public void testSwapSwapsTheTopTwosValueOnTheStackIfTheyAreNotTheOnlyOnes() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 swap"))) + @DisplayName("swap -> swaps the top two values on the stack if they are not the only ones") + public void swapSwapsTheTopTwoValuesOnTheStackIfTheyAreNotTheOnlyOnes() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 swap"))) .containsExactly(1, 3, 2); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfSwappingAttemptedWithNothingOnTheStack() { + @DisplayName("swap -> errors if there is nothing on the stack") + public void swapErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("swap"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("swap"))) .withMessage("Swapping requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfSwappingAttemptedWithOneNumberOnTheStack() { + @DisplayName("swap -> errors if there is only one value on the stack") + public void swapErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 swap"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 swap"))) .withMessage("Swapping requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("copies the second element if there are only two") - public void testOverCopiesTheSecondElementIfThereAreOnlyTwo() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 over"))) + @DisplayName("over -> copies the second element if there are only two") + public void overCopiesTheSecondElementIfThereAreOnlyTwo() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 over"))) .containsExactly(1, 2, 1); } @Disabled("Remove to run test") @Test - @DisplayName("copies the second element if there are more than two") - public void testOverCopiesTheSecondElementIfThereAreMoreThanTwo() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 over"))) + @DisplayName("over -> copies the second element if there are more than two") + public void overCopiesTheSecondElementIfThereAreMoreThanTwo() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 over"))) .containsExactly(1, 2, 3, 2); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is nothing on the stack") - public void testErrorIfOveringAttemptedWithNothingOnTheStack() { + @DisplayName("over -> errors if there is nothing on the stack") + public void overErrorsIfThereIsNothingOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("over"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("over"))) .withMessage("Overing requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if there is only one value on the stack") - public void testErrorIfOveringAttemptedWithOneNumberOnTheStack() { + @DisplayName("over -> errors if there is only one value on the stack") + public void overErrorsIfThereIsOnlyOneValueOnTheStack() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("1 over"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("1 over"))) .withMessage("Overing requires that the stack contain at least 2 values"); } @Disabled("Remove to run test") @Test - @DisplayName("can consist of built-in words") - public void testUserDefinedOperatorsCanConsistOfBuiltInOperators() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": dup-twice dup dup ;", "1 dup-twice"))) + @DisplayName("user-defined words -> can consist of built-in words") + public void userDefinedWordsCanConsistOfBuiltInWords() { + assertThat(forthEvaluator.evaluateProgram(List.of(": dup-twice dup dup ;", "1 dup-twice"))) .containsExactly(1, 1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("execute in the right order") - public void testUserDefinedOperatorsAreEvaluatedInTheCorrectOrder() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": countup 1 2 3 ;", "countup"))) + @DisplayName("user-defined words -> execute in the right order") + public void userDefinedWordsExecuteInTheRightOrder() { + assertThat(forthEvaluator.evaluateProgram(List.of(": countup 1 2 3 ;", "countup"))) .containsExactly(1, 2, 3); } @Disabled("Remove to run test") @Test - @DisplayName("can override other user-defined words") - public void testCanRedefineAUserDefinedOperator() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": foo dup ;", ": foo dup dup ;", "1 foo"))) + @DisplayName("user-defined words -> can override other user-defined words") + public void userDefinedWordsCanOverrideOtherUserDefinedWords() { + assertThat(forthEvaluator.evaluateProgram(List.of(": foo dup ;", ": foo dup dup ;", "1 foo"))) .containsExactly(1, 1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("can override built-in words") - public void testCanOverrideBuiltInWordOperators() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": swap dup ;", "1 swap"))) + @DisplayName("user-defined words -> can override built-in words") + public void userDefinedWordsCanOverrideBuiltInWords() { + assertThat(forthEvaluator.evaluateProgram(List.of(": swap dup ;", "1 swap"))) .containsExactly(1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("can override built-in operators") - public void testCanOverrideBuiltInArithmeticOperators() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": + * ;", "3 4 +"))) + @DisplayName("user-defined words -> can override built-in operators") + public void userDefinedWordsCanOverrideBuiltInOperators() { + assertThat(forthEvaluator.evaluateProgram(List.of(": + * ;", "3 4 +"))) .containsExactly(12); } @Disabled("Remove to run test") @Test - @DisplayName("can use different words with the same name") - public void testCanUseDifferentWordsWithTheSameName() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": foo 5 ;", ": bar foo ;", ": foo 6 ;", "bar foo"))) + @DisplayName("user-defined words -> can use different words with the same name") + public void userDefinedWordsCanUseDifferentWordsWithTheSameName() { + assertThat(forthEvaluator.evaluateProgram(List.of(": foo 5 ;", ": bar foo ;", ": foo 6 ;", "bar foo"))) .containsExactly(5, 6); } @Disabled("Remove to run test") @Test - @DisplayName("can define word that uses word with the same name") - public void testCanDefineWordThatUsesWordWithTheSameName() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": foo 10 ;", ": foo foo 1 + ;", "foo"))) + @DisplayName("user-defined words -> can define word that uses word with the same name") + public void userDefinedWordsCanDefineWordThatUsesWordWithTheSameName() { + assertThat(forthEvaluator.evaluateProgram(List.of(": foo 10 ;", ": foo foo 1 + ;", "foo"))) .containsExactly(11); } @Disabled("Remove to run test") @Test - @DisplayName("cannot redefine non-negative numbers") - public void testCannotRedefineNonNegativeNumbers() { + @DisplayName("user-defined words -> cannot redefine non-negative numbers") + public void userDefinedWordsCannotRedefineNonNegativeNumbers() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList(": 1 2 ;"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of(": 1 2 ;"))) .withMessage("Cannot redefine numbers"); } @Disabled("Remove to run test") @Test - @DisplayName("cannot redefine negative numbers") - public void testCannotRedefineNegativeNumbers() { + @DisplayName("user-defined words -> cannot redefine negative numbers") + public void userDefinedWordsCannotRedefineNegativeNumbers() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList(": -1 2 ;"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of(": -1 2 ;"))) .withMessage("Cannot redefine numbers"); } @Disabled("Remove to run test") @Test - @DisplayName("errors if executing a non-existent word") - public void testErrorIfEvaluatingAnUndefinedOperator() { + @DisplayName("user-defined words -> errors if executing a non-existent word") + public void userDefinedWordsErrorsIfExecutingANonExistentWord() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> forthEvaluator.evaluateProgram(Collections.singletonList("foo"))) + .isThrownBy(() -> forthEvaluator.evaluateProgram(List.of("foo"))) .withMessage("No definition available for operator \"foo\""); } @Disabled("Remove to run test") @Test - @DisplayName("DUP is case-insensitive") - public void testDupIsCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 DUP Dup dup"))) + @DisplayName("user-defined words -> only defines locally") + public void userDefinedWordsOnlyDefinesLocally() { + ForthEvaluator firstInstance = new ForthEvaluator(); + ForthEvaluator secondInstance = new ForthEvaluator(); + + assertThat(firstInstance.evaluateProgram(List.of(": + - ;", "1 1 +"))) + .containsExactly(0); + assertThat(secondInstance.evaluateProgram(List.of("1 1 +"))) + .containsExactly(2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("case-insensitivity -> DUP is case-insensitive") + public void caseInsensitivityDupIsCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 DUP Dup dup"))) .containsExactly(1, 1, 1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("DROP is case-insensitive") - public void testDropIsCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 4 DROP Drop drop"))) + @DisplayName("case-insensitivity -> DROP is case-insensitive") + public void caseInsensitivityDropIsCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 3 4 DROP Drop drop"))) .containsExactly(1); } @Disabled("Remove to run test") @Test - @DisplayName("SWAP is case-insensitive") - public void testSwapIsCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 SWAP 3 Swap 4 swap"))) + @DisplayName("case-insensitivity -> SWAP is case-insensitive") + public void caseInsensitivitySwapIsCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 SWAP 3 Swap 4 swap"))) .containsExactly(2, 3, 4, 1); } @Disabled("Remove to run test") @Test - @DisplayName("OVER is case-insensitive") - public void testOverIsCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 OVER Over over"))) + @DisplayName("case-insensitivity -> OVER is case-insensitive") + public void caseInsensitivityOverIsCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of("1 2 OVER Over over"))) .containsExactly(1, 2, 1, 2, 1); } @Disabled("Remove to run test") @Test - @DisplayName("user-defined words are case-insensitive") - public void testUserDefinedWordsAreCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": foo dup ;", "1 FOO Foo foo"))) + @DisplayName("case-insensitivity -> user-defined words are case-insensitive") + public void caseInsensitivityUserDefinedWordsAreCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of(": foo dup ;", "1 FOO Foo foo"))) .containsExactly(1, 1, 1, 1); } @Disabled("Remove to run test") @Test - @DisplayName("definitions are case-insensitive") - public void testDefinitionsAreCaseInsensitive() { - assertThat(forthEvaluator.evaluateProgram(Arrays.asList(": SWAP DUP Dup dup ;", "1 swap"))) + @DisplayName("case-insensitivity -> definitions are case-insensitive") + public void caseInsensitivityDefinitionsAreCaseInsensitive() { + assertThat(forthEvaluator.evaluateProgram(List.of(": SWAP DUP Dup dup ;", "1 swap"))) .containsExactly(1, 1, 1, 1); } - @Disabled - @Test - @DisplayName("only defines locally") - public void testDefinitionsAreOnlyDefinedLocally() { - ForthEvaluator firstInstance = new ForthEvaluator(); - ForthEvaluator secondInstance = new ForthEvaluator(); - - List firstOutput = firstInstance.evaluateProgram(Arrays.asList(": + - ;", "1 1 +")); - List secondOutput = secondInstance.evaluateProgram(Collections.singletonList("1 1 +")); - - assertThat(firstOutput).containsExactly(0); - assertThat(secondOutput).containsExactly(2); - } - } diff --git a/exercises/practice/game-of-life/src/test/java/GameOfLifeTest.java b/exercises/practice/game-of-life/src/test/java/GameOfLifeTest.java index 9fe627bfd..fd4cf037a 100644 --- a/exercises/practice/game-of-life/src/test/java/GameOfLifeTest.java +++ b/exercises/practice/game-of-life/src/test/java/GameOfLifeTest.java @@ -1,158 +1,114 @@ -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; public class GameOfLifeTest { + @Test - @DisplayName("Empty Matrix") - public void testEmptyMatrix() { + @DisplayName("empty matrix") + public void emptyMatrix() { int[][] matrix = new int[][]{}; - assertThat(new GameOfLife().tick(matrix)).isEmpty(); + int[][] expected = new int[][]{}; + + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Live cells with zero live neighbors die") - public void testLiveCellsWithZeroLiveNeighborsDie() { - int[][] matrix = { - {0, 0, 0}, - {0, 1, 0}, - {0, 0, 0} - }; + @DisplayName("live cells with zero live neighbors die") + public void liveCellsWithZeroLiveNeighborsDie() { + int[][] matrix = new int[][]{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; + int[][] expected = new int[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; - int[][] expected = { - {0, 0, 0}, - {0, 0, 0}, - {0, 0, 0} - }; - - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Live cells with only one live neighbor die") - public void testLiveCellsWithOnlyOneLiveNeighborsDie() { - int[][] matrix = { - {0, 0, 0}, - {0, 1, 0}, - {0, 1, 0}}; - - int[][] expected = { - {0, 0, 0}, - {0, 0, 0}, - {0, 0, 0} - }; + @DisplayName("live cells with only one live neighbor die") + public void liveCellsWithOnlyOneLiveNeighborDie() { + int[][] matrix = new int[][]{{0, 0, 0}, {0, 1, 0}, {0, 1, 0}}; + int[][] expected = new int[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Live cells with two live neighbors stay alive") - public void testLiveCellsWithTwoLiveNeighborsStayAlive() { - int[][] matrix = { - {1, 0, 1}, - {1, 0, 1}, - {1, 0, 1} - }; - - int[][] expected = { - {0, 0, 0}, - {1, 0, 1}, - {0, 0, 0} - }; + @DisplayName("live cells with two live neighbors stay alive") + public void liveCellsWithTwoLiveNeighborsStayAlive() { + int[][] matrix = new int[][]{{1, 0, 1}, {1, 0, 1}, {1, 0, 1}}; + int[][] expected = new int[][]{{0, 0, 0}, {1, 0, 1}, {0, 0, 0}}; - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Live cells with three live neighbors stay alive") - public void testLiveCellsWithThreeLiveNeighborsStayAlive() { - int[][] matrix = { - {0, 1, 0}, - {1, 0, 0}, - {1, 1, 0} - }; - - int[][] expected = { - {0, 0, 0}, - {1, 0, 0}, - {1, 1, 0} - - }; + @DisplayName("live cells with three live neighbors stay alive") + public void liveCellsWithThreeLiveNeighborsStayAlive() { + int[][] matrix = new int[][]{{0, 1, 0}, {1, 0, 0}, {1, 1, 0}}; + int[][] expected = new int[][]{{0, 0, 0}, {1, 0, 0}, {1, 1, 0}}; - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Dead cells with three live neighbors become alive") - public void testDeadCellsWithThreeLiveNeighborsBecomeAlive() { - int[][] matrix = { - {1, 1, 0}, - {0, 0, 0}, - {1, 0, 0} - }; + @DisplayName("dead cells with three live neighbors become alive") + public void deadCellsWithThreeLiveNeighborsBecomeAlive() { + int[][] matrix = new int[][]{{1, 1, 0}, {0, 0, 0}, {1, 0, 0}}; + int[][] expected = new int[][]{{0, 0, 0}, {1, 1, 0}, {0, 0, 0}}; - int[][] expected = { - {0, 0, 0}, - {1, 1, 0}, - {0, 0, 0} - }; - - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Live cells with four or more neighbors die") - public void testLiveCellsWithFourOrMoreNeighborsDie() { - int[][] matrix = { - {1, 1, 1}, - {1, 1, 1}, - {1, 1, 1} - }; + @DisplayName("live cells with four or more neighbors die") + public void liveCellsWithFourOrMoreNeighborsDie() { + int[][] matrix = new int[][]{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}; + int[][] expected = new int[][]{{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}; - int[][] expected = { - {1, 0, 1}, - {0, 0, 0}, - {1, 0, 1} - }; - - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Bigger Matrix") - public void testBiggerMatrix () { - int[][] matrix = { - {1, 1, 0, 1, 1, 0, 0, 0}, - {1, 0, 1, 1, 0, 0, 0, 0}, - {1, 1, 1, 0, 0, 1, 1, 1}, - {0, 0, 0, 0, 0, 1, 1, 0}, - {1, 0, 0, 0, 1, 1, 0, 0}, - {1, 1, 0, 0, 0, 1, 1, 1}, - {0, 0, 1, 0, 1, 0, 0, 1}, - {1, 0, 0, 0, 0, 0, 1, 1} + @DisplayName("bigger matrix") + public void biggerMatrix() { + int[][] matrix = new int[][]{ + {1, 1, 0, 1, 1, 0, 0, 0}, + {1, 0, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 0, 0, 1, 1, 1}, + {0, 0, 0, 0, 0, 1, 1, 0}, + {1, 0, 0, 0, 1, 1, 0, 0}, + {1, 1, 0, 0, 0, 1, 1, 1}, + {0, 0, 1, 0, 1, 0, 0, 1}, + {1, 0, 0, 0, 0, 0, 1, 1} }; - - int[][] expected = { - {1, 1, 0, 1, 1, 0, 0, 0}, - {0, 0, 0, 0, 0, 1, 1, 0}, - {1, 0, 1, 1, 1, 1, 0, 1}, - {1, 0, 0, 0, 0, 0, 0, 1}, - {1, 1, 0, 0, 1, 0, 0, 1}, - {1, 1, 0, 1, 0, 0, 0, 1}, - {1, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 1, 1} + int[][] expected = new int[][]{ + {1, 1, 0, 1, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 1, 1, 0}, + {1, 0, 1, 1, 1, 1, 0, 1}, + {1, 0, 0, 0, 0, 0, 0, 1}, + {1, 1, 0, 0, 1, 0, 0, 1}, + {1, 1, 0, 1, 0, 0, 0, 1}, + {1, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 1, 1} }; - assertThat(new GameOfLife().tick(matrix)).isEqualTo(expected); + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); } } diff --git a/exercises/practice/gigasecond/src/test/java/GigasecondTest.java b/exercises/practice/gigasecond/src/test/java/GigasecondTest.java index 2f5872fdd..3b4d72e33 100644 --- a/exercises/practice/gigasecond/src/test/java/GigasecondTest.java +++ b/exercises/practice/gigasecond/src/test/java/GigasecondTest.java @@ -4,7 +4,6 @@ import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.Month; import static org.assertj.core.api.Assertions.assertThat; @@ -12,55 +11,51 @@ public class GigasecondTest { @Test @DisplayName("date only specification of time") - public void modernTime() { - Gigasecond gigaSecond = new Gigasecond(LocalDate.of(2011, Month.APRIL, 25)); - - assertThat(gigaSecond.getDateTime()).isEqualTo(LocalDateTime.of(2043, Month.JANUARY, 1, 1, 46, 40)); + public void dateOnlySpecificationOfTime() { + assertThat(new Gigasecond(LocalDate.parse("2011-04-25")).getDateTime()) + .isEqualTo(LocalDateTime.parse("2043-01-01T01:46:40")); } @Disabled("Remove to run test") @Test @DisplayName("second test for date only specification of time") - public void afterEpochTime() { - Gigasecond gigaSecond = new Gigasecond(LocalDate.of(1977, Month.JUNE, 13)); - - assertThat(gigaSecond.getDateTime()).isEqualTo(LocalDateTime.of(2009, Month.FEBRUARY, 19, 1, 46, 40)); + public void secondTestForDateOnlySpecificationOfTime() { + assertThat(new Gigasecond(LocalDate.parse("1977-06-13")).getDateTime()) + .isEqualTo(LocalDateTime.parse("2009-02-19T01:46:40")); } @Disabled("Remove to run test") @Test @DisplayName("third test for date only specification of time") - public void beforeEpochTime() { - Gigasecond gigaSecond = new Gigasecond(LocalDate.of(1959, Month.JULY, 19)); - - assertThat(gigaSecond.getDateTime()).isEqualTo(LocalDateTime.of(1991, Month.MARCH, 27, 1, 46, 40)); + public void thirdTestForDateOnlySpecificationOfTime() { + assertThat(new Gigasecond(LocalDate.parse("1959-07-19")).getDateTime()) + .isEqualTo(LocalDateTime.parse("1991-03-27T01:46:40")); } @Disabled("Remove to run test") @Test @DisplayName("full time specified") - public void withFullTimeSpecified() { - Gigasecond gigaSecond = new Gigasecond(LocalDateTime.of(2015, Month.JANUARY, 24, 22, 0, 0)); - - assertThat(gigaSecond.getDateTime()).isEqualTo(LocalDateTime.of(2046, Month.OCTOBER, 2, 23, 46, 40)); + public void fullTimeSpecified() { + assertThat(new Gigasecond(LocalDateTime.parse("2015-01-24T22:00:00")).getDateTime()) + .isEqualTo(LocalDateTime.parse("2046-10-02T23:46:40")); } @Disabled("Remove to run test") @Test @DisplayName("full time with day roll-over") - public void withFullTimeSpecifiedAndDayRollover() { - Gigasecond gigaSecond = new Gigasecond(LocalDateTime.of(2015, Month.JANUARY, 24, 23, 59, 59)); - - assertThat(gigaSecond.getDateTime()).isEqualTo(LocalDateTime.of(2046, Month.OCTOBER, 3, 1, 46, 39)); + public void fullTimeWithDayRollOver() { + assertThat(new Gigasecond(LocalDateTime.parse("2015-01-24T23:59:59")).getDateTime()) + .isEqualTo(LocalDateTime.parse("2046-10-03T01:46:39")); } @Disabled("Remove to run test") @Test @DisplayName("does not mutate the input") - public void doesNotMutateInput() { - LocalDateTime input = LocalDateTime.of(2015, Month.JANUARY, 24, 23, 59, 59); + public void doesNotMutateTheInput() { + LocalDateTime input = LocalDateTime.parse("2015-01-24T23:59:59"); new Gigasecond(input).getDateTime(); - assertThat(input).isEqualTo(LocalDateTime.of(2015, Month.JANUARY, 24, 23, 59, 59)); + assertThat(input).isEqualTo(LocalDateTime.parse("2015-01-24T23:59:59")); } + } diff --git a/exercises/practice/go-counting/src/test/java/GoCountingTest.java b/exercises/practice/go-counting/src/test/java/GoCountingTest.java index 2b336088c..dcfa8918f 100644 --- a/exercises/practice/go-counting/src/test/java/GoCountingTest.java +++ b/exercises/practice/go-counting/src/test/java/GoCountingTest.java @@ -2,9 +2,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.awt.*; -import java.util.HashMap; -import java.util.HashSet; +import java.awt.Point; +import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -12,72 +11,71 @@ public class GoCountingTest { - String board5x5 = " B \n" + - " B B \n" + - "B W B\n" + - " W W \n" + - " W "; - @Test @DisplayName("Black corner territory on 5x5 board") - public void blackCorner5x5BoardTest() { - GoCounting gocounting = new GoCounting(board5x5); - - Set territory = new HashSet<>(); - territory.add(new Point(0, 0)); - territory.add(new Point(0, 1)); - territory.add(new Point(1, 0)); - + public void blackCornerTerritoryOn5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThat(gocounting.getTerritoryOwner(0, 1)).isEqualTo(Player.BLACK); - assertThat(gocounting.getTerritory(0, 1)).isEqualTo(territory); + assertThat(gocounting.getTerritory(0, 1)).isEqualTo(Set.of(new Point(0, 0), new Point(0, 1), new Point(1, 0))); } @Disabled("Remove to run test") @Test @DisplayName("White center territory on 5x5 board") - public void whiteCenter5x5BoardTest() { - GoCounting gocounting = new GoCounting(board5x5); - - Set territory = new HashSet<>(); - territory.add(new Point(2, 3)); - + public void whiteCenterTerritoryOn5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThat(gocounting.getTerritoryOwner(2, 3)).isEqualTo(Player.WHITE); - assertThat(gocounting.getTerritory(2, 3)).isEqualTo(territory); + assertThat(gocounting.getTerritory(2, 3)).isEqualTo(Set.of(new Point(2, 3))); } @Disabled("Remove to run test") @Test @DisplayName("Open corner territory on 5x5 board") - public void openCorner5x5BoardTest() { - GoCounting gocounting = new GoCounting(board5x5); - - Set territory = new HashSet<>(); - territory.add(new Point(0, 3)); - territory.add(new Point(0, 4)); - territory.add(new Point(1, 4)); - + public void openCornerTerritoryOn5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThat(gocounting.getTerritoryOwner(1, 4)).isEqualTo(Player.NONE); - assertThat(gocounting.getTerritory(1, 4)).isEqualTo(territory); + assertThat(gocounting.getTerritory(1, 4)).isEqualTo(Set.of(new Point(0, 3), new Point(0, 4), new Point(1, 4))); } @Disabled("Remove to run test") @Test @DisplayName("A stone and not a territory on 5x5 board") - public void stoneNotTerritory5x5Board() { - GoCounting gocounting = new GoCounting(board5x5); - - Set territory = new HashSet<>(); - + public void aStoneAndNotATerritoryOn5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThat(gocounting.getTerritoryOwner(1, 1)).isEqualTo(Player.NONE); - assertThat(gocounting.getTerritory(1, 1)).isEqualTo(territory); + assertThat(gocounting.getTerritory(1, 1)).isEqualTo(Set.of()); } @Disabled("Remove to run test") @Test @DisplayName("Invalid because X is too low for 5x5 board") - public void invalidXTooLow5x5Board() { - GoCounting gocounting = new GoCounting(board5x5); - + public void invalidBecauseXIsTooLowFor5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> gocounting.getTerritory(-1, 1)) .withMessage("Invalid coordinate"); @@ -86,9 +84,13 @@ public void invalidXTooLow5x5Board() { @Disabled("Remove to run test") @Test @DisplayName("Invalid because X is too high for 5x5 board") - public void invalidXTooHigh5x5Board() { - GoCounting gocounting = new GoCounting(board5x5); - + public void invalidBecauseXIsTooHighFor5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> gocounting.getTerritory(5, 1)) .withMessage("Invalid coordinate"); @@ -97,9 +99,13 @@ public void invalidXTooHigh5x5Board() { @Disabled("Remove to run test") @Test @DisplayName("Invalid because Y is too low for 5x5 board") - public void invalidYTooLow5x5Board() { - GoCounting gocounting = new GoCounting(board5x5); - + public void invalidBecauseYIsTooLowFor5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> gocounting.getTerritory(1, -1)) .withMessage("Invalid coordinate"); @@ -108,9 +114,13 @@ public void invalidYTooLow5x5Board() { @Disabled("Remove to run test") @Test @DisplayName("Invalid because Y is too high for 5x5 board") - public void invalidYTooHigh5x5Board() { - GoCounting gocounting = new GoCounting(board5x5); - + public void invalidBecauseYIsTooHighFor5x5Board() { + GoCounting gocounting = new GoCounting( + " B \n" + + " B B \n" + + "B W B\n" + + " W W \n" + + " W \n"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> gocounting.getTerritory(1, 5)) .withMessage("Invalid coordinate"); @@ -119,63 +129,51 @@ public void invalidYTooHigh5x5Board() { @Disabled("Remove to run test") @Test @DisplayName("One territory is the whole board") - public void oneTerritoryIsWholeBoardTest() { + public void oneTerritoryIsTheWholeBoard() { GoCounting gocounting = new GoCounting(" "); - - HashMap> territories = new HashMap<>(); - Set blackTerritory = new HashSet<>(); - Set whiteTerritory = new HashSet<>(); - Set noneTerritory = new HashSet<>(); - noneTerritory.add(new Point(0, 0)); - - territories.put(Player.BLACK, blackTerritory); - territories.put(Player.WHITE, whiteTerritory); - territories.put(Player.NONE, noneTerritory); - - assertThat(gocounting.getTerritories()).isEqualTo(territories); + Set territoryBlack = Set.of(); + Set territoryWhite = Set.of(); + Set territoryNone = Set.of(new Point(0, 0)); + Map> expected = Map.of( + Player.BLACK, territoryBlack, + Player.WHITE, territoryWhite, + Player.NONE, territoryNone + ); + assertThat(gocounting.getTerritories()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("Two territory rectangular board") - public void twoTerritoryRectangularBoardTest() { - GoCounting gocounting = new GoCounting(" BW \n BW "); - - Set blackTerritory = new HashSet<>(); - blackTerritory.add(new Point(0, 0)); - blackTerritory.add(new Point(0, 1)); - - Set whiteTerritory = new HashSet<>(); - whiteTerritory.add(new Point(3, 0)); - whiteTerritory.add(new Point(3, 1)); - - Set noneTerritory = new HashSet<>(); - - HashMap> territories = new HashMap<>(); - territories.put(Player.BLACK, blackTerritory); - territories.put(Player.WHITE, whiteTerritory); - territories.put(Player.NONE, noneTerritory); - - assertThat(gocounting.getTerritories()).isEqualTo(territories); + public void twoTerritoryRectangularBoard() { + GoCounting gocounting = new GoCounting( + " BW \n" + + " BW \n"); + Set territoryBlack = Set.of(new Point(0, 0), new Point(0, 1)); + Set territoryWhite = Set.of(new Point(3, 0), new Point(3, 1)); + Set territoryNone = Set.of(); + Map> expected = Map.of( + Player.BLACK, territoryBlack, + Player.WHITE, territoryWhite, + Player.NONE, territoryNone + ); + assertThat(gocounting.getTerritories()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("Two region rectangular board") - public void twoRegionRectangularBoardTest() { + public void twoRegionRectangularBoard() { GoCounting gocounting = new GoCounting(" B "); - - HashMap> territories = new HashMap<>(); - Set blackTerritory = new HashSet<>(); - blackTerritory.add(new Point(0, 0)); - blackTerritory.add(new Point(2, 0)); - Set whiteTerritory = new HashSet<>(); - Set noneTerritory = new HashSet<>(); - - territories.put(Player.BLACK, blackTerritory); - territories.put(Player.WHITE, whiteTerritory); - territories.put(Player.NONE, noneTerritory); - - assertThat(gocounting.getTerritories()).isEqualTo(territories); + Set territoryBlack = Set.of(new Point(0, 0), new Point(2, 0)); + Set territoryWhite = Set.of(); + Set territoryNone = Set.of(); + Map> expected = Map.of( + Player.BLACK, territoryBlack, + Player.WHITE, territoryWhite, + Player.NONE, territoryNone + ); + assertThat(gocounting.getTerritories()).isEqualTo(expected); } + } diff --git a/exercises/practice/grade-school/src/test/java/SchoolTest.java b/exercises/practice/grade-school/src/test/java/SchoolTest.java index 10a7fd728..fc44064a5 100644 --- a/exercises/practice/grade-school/src/test/java/SchoolTest.java +++ b/exercises/practice/grade-school/src/test/java/SchoolTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,16 +5,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class SchoolTest { - private School school; - - @BeforeEach - public void setUp() { - school = new School(); - } @Test @DisplayName("Roster is empty when no student is added") - public void rosterReturnsAnEmptyListIfThereAreNoStudentsEnrolled() { + public void rosterIsEmptyWhenNoStudentIsAdded() { + School school = new School(); assertThat(school.roster()).isEmpty(); } @@ -23,22 +17,24 @@ public void rosterReturnsAnEmptyListIfThereAreNoStudentsEnrolled() { @Test @DisplayName("Add a student") public void addAStudent() { + School school = new School(); assertThat(school.add("Aimee", 2)).isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("Student is added to the roster") - public void addingAStudentAddsThemToTheSortedRoster() { + public void studentIsAddedToTheRoster() { + School school = new School(); school.add("Aimee", 2); - assertThat(school.roster()).containsExactly("Aimee"); } @Disabled("Remove to run test") @Test @DisplayName("Adding multiple students in the same grade in the roster") - public void addingMultipleStudentsInTheSameGrade() { + public void addingMultipleStudentsInTheSameGradeInTheRoster() { + School school = new School(); assertThat(school.add("Blair", 2)).isTrue(); assertThat(school.add("James", 2)).isTrue(); assertThat(school.add("Paul", 2)).isTrue(); @@ -47,18 +43,19 @@ public void addingMultipleStudentsInTheSameGrade() { @Disabled("Remove to run test") @Test @DisplayName("Multiple students in the same grade are added to the roster") - public void addingMoreStudentsAddsThemToTheSameSortedRoster() { + public void multipleStudentsInTheSameGradeAreAddedToTheRoster() { + School school = new School(); school.add("Blair", 2); school.add("James", 2); school.add("Paul", 2); - assertThat(school.roster()).containsExactly("Blair", "James", "Paul"); } @Disabled("Remove to run test") @Test @DisplayName("Cannot add student to same grade in the roster more than once") - public void cannotAddStudentsToSameGradeInTheRosterMoreThanOnce() { + public void cannotAddStudentToSameGradeInTheRosterMoreThanOnce() { + School school = new School(); assertThat(school.add("Blair", 2)).isTrue(); assertThat(school.add("James", 2)).isTrue(); assertThat(school.add("James", 2)).isFalse(); @@ -69,11 +66,11 @@ public void cannotAddStudentsToSameGradeInTheRosterMoreThanOnce() { @Test @DisplayName("Student not added to same grade in the roster more than once") public void studentNotAddedToSameGradeInTheRosterMoreThanOnce() { + School school = new School(); school.add("Blair", 2); school.add("James", 2); school.add("James", 2); school.add("Paul", 2); - assertThat(school.roster()).containsExactly("Blair", "James", "Paul"); } @@ -81,6 +78,7 @@ public void studentNotAddedToSameGradeInTheRosterMoreThanOnce() { @Test @DisplayName("Adding students in multiple grades") public void addingStudentsInMultipleGrades() { + School school = new School(); assertThat(school.add("Chelsea", 3)).isTrue(); assertThat(school.add("Logan", 7)).isTrue(); } @@ -88,10 +86,10 @@ public void addingStudentsInMultipleGrades() { @Disabled("Remove to run test") @Test @DisplayName("Students in multiple grades are added to the roster") - public void addingStudentsToDifferentGradesAddsThemToTheSameSortedRoster() { + public void studentsInMultipleGradesAreAddedToTheRoster() { + School school = new School(); school.add("Chelsea", 3); school.add("Logan", 7); - assertThat(school.roster()).containsExactly("Chelsea", "Logan"); } @@ -99,6 +97,7 @@ public void addingStudentsToDifferentGradesAddsThemToTheSameSortedRoster() { @Test @DisplayName("Cannot add same student to multiple grades in the roster") public void cannotAddSameStudentToMultipleGradesInTheRoster() { + School school = new School(); assertThat(school.add("Blair", 2)).isTrue(); assertThat(school.add("James", 2)).isTrue(); assertThat(school.add("James", 3)).isFalse(); @@ -109,22 +108,22 @@ public void cannotAddSameStudentToMultipleGradesInTheRoster() { @Test @DisplayName("Student not added to multiple grades in the roster") public void studentNotAddedToMultipleGradesInTheRoster() { + School school = new School(); school.add("Blair", 2); school.add("James", 2); school.add("James", 3); school.add("Paul", 3); - assertThat(school.roster()).containsExactly("Blair", "James", "Paul"); } @Disabled("Remove to run test") @Test @DisplayName("Students are sorted by grades in the roster") - public void studentsAreSortedByGradeInTheRoster() { + public void studentsAreSortedByGradesInTheRoster() { + School school = new School(); school.add("Jim", 3); school.add("Peter", 2); school.add("Anna", 1); - assertThat(school.roster()).containsExactly("Anna", "Peter", "Jim"); } @@ -132,17 +131,18 @@ public void studentsAreSortedByGradeInTheRoster() { @Test @DisplayName("Students are sorted by name in the roster") public void studentsAreSortedByNameInTheRoster() { + School school = new School(); school.add("Peter", 2); school.add("Zoe", 2); school.add("Alex", 2); - assertThat(school.roster()).containsExactly("Alex", "Peter", "Zoe"); } @Disabled("Remove to run test") @Test @DisplayName("Students are sorted by grades and then by name in the roster") - public void studentsAreSortedByGradeAndThenByNameInTheRoster() { + public void studentsAreSortedByGradesAndThenByNameInTheRoster() { + School school = new School(); school.add("Peter", 2); school.add("Anna", 1); school.add("Barb", 1); @@ -150,7 +150,6 @@ public void studentsAreSortedByGradeAndThenByNameInTheRoster() { school.add("Alex", 2); school.add("Jim", 3); school.add("Charlie", 1); - assertThat(school.roster()).containsExactly("Anna", "Barb", "Charlie", "Alex", "Peter", "Zoe", "Jim"); } @@ -158,6 +157,7 @@ public void studentsAreSortedByGradeAndThenByNameInTheRoster() { @Test @DisplayName("Grade is empty if no students in the roster") public void gradeIsEmptyIfNoStudentsInTheRoster() { + School school = new School(); assertThat(school.grade(1)).isEmpty(); } @@ -165,47 +165,63 @@ public void gradeIsEmptyIfNoStudentsInTheRoster() { @Test @DisplayName("Grade is empty if no students in that grade") public void gradeIsEmptyIfNoStudentsInThatGrade() { + School school = new School(); school.add("Peter", 2); school.add("Zoe", 2); school.add("Alex", 2); school.add("Jim", 3); - assertThat(school.grade(1)).isEmpty(); } @Disabled("Remove to run test") @Test @DisplayName("Student not added to same grade more than once") - public void studentNotAddedToTheSameGradeMoreThanOnce() { + public void studentNotAddedToSameGradeMoreThanOnce() { + School school = new School(); school.add("Blair", 2); school.add("James", 2); school.add("James", 2); school.add("Paul", 2); - - assertThat(school.grade(2)).containsExactly("Blair", "James", "Paul"); + assertThat(school.grade(2)) + .containsExactly("Blair", "James", "Paul"); } @Disabled("Remove to run test") @Test @DisplayName("Student not added to multiple grades") public void studentNotAddedToMultipleGrades() { + School school = new School(); school.add("Blair", 2); school.add("James", 2); school.add("James", 3); school.add("Paul", 3); + assertThat(school.grade(2)) + .containsExactly("Blair", "James"); + } - assertThat(school.grade(2)).containsExactly("Blair", "James"); - assertThat(school.grade(3)).containsExactly("Paul"); + @Disabled("Remove to run test") + @Test + @DisplayName("Student not added to other grade for multiple grades") + public void studentNotAddedToOtherGradeForMultipleGrades() { + School school = new School(); + school.add("Blair", 2); + school.add("James", 2); + school.add("James", 3); + school.add("Paul", 3); + assertThat(school.grade(3)) + .containsExactly("Paul"); } @Disabled("Remove to run test") @Test @DisplayName("Students are sorted by name in a grade") public void studentsAreSortedByNameInAGrade() { + School school = new School(); school.add("Franklin", 5); school.add("Bradley", 5); school.add("Jeff", 1); - - assertThat(school.grade(5)).containsExactly("Bradley", "Franklin"); + assertThat(school.grade(5)) + .containsExactly("Bradley", "Franklin"); } + } diff --git a/exercises/practice/grains/src/test/java/GrainsTest.java b/exercises/practice/grains/src/test/java/GrainsTest.java index a09e48e88..233850ab7 100644 --- a/exercises/practice/grains/src/test/java/GrainsTest.java +++ b/exercises/practice/grains/src/test/java/GrainsTest.java @@ -12,93 +12,115 @@ public class GrainsTest { private Grains grains = new Grains(); @Test - @DisplayName("returns the number of grains on the square") - public void countAtSquare1() { - BigInteger result = grains.grainsOnSquare(1); - assertThat(result).isEqualTo(new BigInteger("1")); + @DisplayName("returns the number of grains on the square -> grains on square 1") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare1() { + + assertThat(grains.grainsOnSquare(1)) + .isEqualTo(new BigInteger("1")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 2") - public void countAtSquare2() { - BigInteger result = grains.grainsOnSquare(2); - assertThat(result).isEqualTo(new BigInteger("2")); + @DisplayName("returns the number of grains on the square -> grains on square 2") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare2() { + + assertThat(grains.grainsOnSquare(2)) + .isEqualTo(new BigInteger("2")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 3") - public void countAtSquare3() { - BigInteger result = grains.grainsOnSquare(3); - assertThat(result).isEqualTo(new BigInteger("4")); + @DisplayName("returns the number of grains on the square -> grains on square 3") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare3() { + + assertThat(grains.grainsOnSquare(3)) + .isEqualTo(new BigInteger("4")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 4") - public void countAtSquare4() { - BigInteger result = grains.grainsOnSquare(4); - assertThat(result).isEqualTo(new BigInteger("8")); + @DisplayName("returns the number of grains on the square -> grains on square 4") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare4() { + + assertThat(grains.grainsOnSquare(4)) + .isEqualTo(new BigInteger("8")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 16") - public void countAtSquare16() { - BigInteger result = grains.grainsOnSquare(16); - assertThat(result).isEqualTo(new BigInteger("32768")); + @DisplayName("returns the number of grains on the square -> grains on square 16") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare16() { + + assertThat(grains.grainsOnSquare(16)) + .isEqualTo(new BigInteger("32768")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 32") - public void countAtSquare32() { - BigInteger result = grains.grainsOnSquare(32); - assertThat(result).isEqualTo(new BigInteger("2147483648")); + @DisplayName("returns the number of grains on the square -> grains on square 32") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare32() { + + assertThat(grains.grainsOnSquare(32)) + .isEqualTo(new BigInteger("2147483648")); + } @Disabled("Remove to run test") @Test - @DisplayName("grains on square 64") - public void countAtSquare64() { - BigInteger result = grains.grainsOnSquare(64); - assertThat(result).isEqualTo(new BigInteger("9223372036854775808")); + @DisplayName("returns the number of grains on the square -> grains on square 64") + public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare64() { + + assertThat(grains.grainsOnSquare(64)) + .isEqualTo(new BigInteger("9223372036854775808")); + } @Disabled("Remove to run test") @Test - @DisplayName("square 0 is invalid") - public void errorOnNullBoardSize() { + @DisplayName("returns the number of grains on the square -> square 0 is invalid") + public void returnsTheNumberOfGrainsOnTheSquareSquare0IsInvalid() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(0)) .withMessage("square must be between 1 and 64"); + } @Disabled("Remove to run test") @Test - @DisplayName("negative square is invalid") - public void errorOnNegativeBoardSize() { + @DisplayName("returns the number of grains on the square -> negative square is invalid") + public void returnsTheNumberOfGrainsOnTheSquareNegativeSquareIsInvalid() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(-1)) .withMessage("square must be between 1 and 64"); + } @Disabled("Remove to run test") @Test - @DisplayName("square greater than 64 is invalid") - public void errorOnExcessiveBoardSize() { + @DisplayName("returns the number of grains on the square -> square greater than 64 is invalid") + public void returnsTheNumberOfGrainsOnTheSquareSquareGreaterThan64IsInvalid() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(65)) .withMessage("square must be between 1 and 64"); + } @Disabled("Remove to run test") @Test @DisplayName("returns the total number of grains on the board") - public void totalNumberOfGrainsOnABoard() { - BigInteger total = grains.grainsOnBoard(); - assertThat(total).isEqualTo(new BigInteger("18446744073709551615")); + public void returnsTheTotalNumberOfGrainsOnTheBoard() { + + assertThat(grains.grainsOnBoard()) + .isEqualTo(new BigInteger("18446744073709551615")); + } } diff --git a/exercises/practice/grep/src/test/java/GrepToolTest.java b/exercises/practice/grep/src/test/java/GrepToolTest.java index d6d27816d..24789d032 100644 --- a/exercises/practice/grep/src/test/java/GrepToolTest.java +++ b/exercises/practice/grep/src/test/java/GrepToolTest.java @@ -5,22 +5,21 @@ import org.junit.jupiter.api.Test; import java.io.IOException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class GrepToolTest { + private GrepTool grepTool; @BeforeEach public void setUp() throws IOException { - List iliadText = Arrays.asList( + List iliadText = List.of( "Achilles sing, O Goddess! Peleus' son;", "His wrath pernicious, who ten thousand woes", "Caused to Achaia's host, sent many a soul", @@ -33,7 +32,7 @@ public void setUp() throws IOException { ); writeToFile("iliad.txt", iliadText); - List midsummerNightText = Arrays.asList( + List midsummerNightText = List.of( "I do entreat your grace to pardon me.", "I know not by what power I am made bold,", "Nor how it may concern my modesty,", @@ -44,7 +43,7 @@ public void setUp() throws IOException { ); writeToFile("midsummer-night.txt", midsummerNightText); - List paradiseLostText = Arrays.asList( + List paradiseLostText = List.of( "Of Mans First Disobedience, and the Fruit", "Of that Forbidden Tree, whose mortal tast", "Brought Death into the World, and all our woe,", @@ -67,438 +66,347 @@ public void tearDown() throws IOException { } @Test - @DisplayName("One file, one match, no flags") - public void oneFileOneMatchNoFlags() { - String expected = "Of Atreus, Agamemnon, King of men."; - - String actual = grepTool.grep( - "Agamemnon", - Collections.emptyList(), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, no flags") + public void testGreppingASingleFileOneFileOneMatchNoFlags() { + assertThat(grepTool.grep( + "Agamemnon", + List.of(), + List.of("iliad.txt"))) + .isEqualTo("Of Atreus, Agamemnon, King of men."); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, print line numbers flag") - public void oneFileOneMatchPrintLineNumbersFlag() { - String expected = "2:Of that Forbidden Tree, whose mortal tast"; - - String actual = grepTool.grep( - "Forbidden", - Collections.singletonList("-n"), - Collections.singletonList("paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, print line numbers flag") + public void testGreppingASingleFileOneFileOneMatchPrintLineNumbersFlag() { + assertThat(grepTool.grep( + "Forbidden", + List.of("-n"), + List.of("paradise-lost.txt"))) + .isEqualTo("2:Of that Forbidden Tree, whose mortal tast"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, case-insensitive flag") - public void oneFileOneMatchCaseInsensitiveFlag() { - String expected = "Of that Forbidden Tree, whose mortal tast"; - - String actual = grepTool.grep( - "FORBIDDEN", - Collections.singletonList("-i"), - Collections.singletonList("paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, case-insensitive flag") + public void testGreppingASingleFileOneFileOneMatchCaseInsensitiveFlag() { + assertThat(grepTool.grep( + "FORBIDDEN", + List.of("-i"), + List.of("paradise-lost.txt"))) + .isEqualTo("Of that Forbidden Tree, whose mortal tast"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, print file names flag") - public void oneFileOneMatchPrintFileNamesFlag() { - String expected = "paradise-lost.txt"; - - String actual = grepTool.grep( - "Forbidden", - Collections.singletonList("-l"), - Collections.singletonList("paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, print file names flag") + public void testGreppingASingleFileOneFileOneMatchPrintFileNamesFlag() { + assertThat(grepTool.grep( + "Forbidden", + List.of("-l"), + List.of("paradise-lost.txt"))) + .isEqualTo("paradise-lost.txt"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, match entire lines flag") - public void oneFileOneMatchEntireLinesFlag() { - String expected = "With loss of Eden, till one greater Man"; - - String actual = grepTool.grep( - "With loss of Eden, till one greater Man", - Collections.singletonList("-x"), - Collections.singletonList("paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, match entire lines flag") + public void testGreppingASingleFileOneFileOneMatchMatchEntireLinesFlag() { + assertThat(grepTool.grep( + "With loss of Eden, till one greater Man", + List.of("-x"), + List.of("paradise-lost.txt"))) + .isEqualTo("With loss of Eden, till one greater Man"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, multiple flags") - public void oneFileOneMatchMultipleFlags() { - String expected = "9:Of Atreus, Agamemnon, King of men."; - - String actual = grepTool.grep( - "OF ATREUS, Agamemnon, KIng of MEN.", - Arrays.asList("-n", "-i", "-x"), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, multiple flags") + public void testGreppingASingleFileOneFileOneMatchMultipleFlags() { + assertThat(grepTool.grep( + "OF ATREUS, Agamemnon, KIng of MEN.", + List.of("-n", "-i", "-x"), + List.of("iliad.txt"))) + .isEqualTo("9:Of Atreus, Agamemnon, King of men."); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, no flags") - public void oneFileSeveralMatchesNoFlags() { - String expected = "Nor how it may concern my modesty,\n" - + "But I beseech your grace that I may know\n" - + "The worst that may befall me in this case,"; - - String actual = grepTool.grep( - "may", - Collections.emptyList(), - Collections.singletonList("midsummer-night.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, no flags") + public void testGreppingASingleFileOneFileSeveralMatchesNoFlags() { + assertThat(grepTool.grep( + "may", + List.of(), + List.of("midsummer-night.txt"))) + .isEqualTo("Nor how it may concern my modesty,\n" + + "But I beseech your grace that I may know\n" + + "The worst that may befall me in this case,"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, print line numbers flag") - public void oneFileSeveralMatchesPrintLineNumbersFlag() { - String expected = "3:Nor how it may concern my modesty,\n" - + "5:But I beseech your grace that I may know\n" - + "6:The worst that may befall me in this case,"; - - String actual = grepTool.grep( - "may", - Collections.singletonList("-n"), - Collections.singletonList("midsummer-night.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, print line numbers flag") + public void testGreppingASingleFileOneFileSeveralMatchesPrintLineNumbersFlag() { + assertThat(grepTool.grep( + "may", + List.of("-n"), + List.of("midsummer-night.txt"))) + .isEqualTo("3:Nor how it may concern my modesty,\n" + + "5:But I beseech your grace that I may know\n" + + "6:The worst that may befall me in this case,"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, match entire lines flag") - public void oneFileSeveralMatchesMatchEntireLineFlag() { - String expected = ""; - - String actual = grepTool.grep( - "may", - Collections.singletonList("-x"), - Collections.singletonList("midsummer-night.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, match entire lines flag") + public void testGreppingASingleFileOneFileSeveralMatchesMatchEntireLinesFlag() { + assertThat(grepTool.grep( + "may", + List.of("-x"), + List.of("midsummer-night.txt"))) + .isEqualTo(""); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, case-insensitive flag") - public void oneFileSeveralMatchesCaseInsensitiveFlag() { - String expected = "Achilles sing, O Goddess! Peleus' son;\n" - + "The noble Chief Achilles from the son"; - - String actual = grepTool.grep( - "ACHILLES", - Collections.singletonList("-i"), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, case-insensitive flag") + public void testGreppingASingleFileOneFileSeveralMatchesCaseInsensitiveFlag() { + assertThat(grepTool.grep( + "ACHILLES", + List.of("-i"), + List.of("iliad.txt"))) + .isEqualTo("Achilles sing, O Goddess! Peleus' son;\n" + + "The noble Chief Achilles from the son"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, inverted flag") - public void oneFileSeveralMatchesInvertedFlag() { - String expected = "Brought Death into the World, and all our woe,\n" - + "With loss of Eden, till one greater Man\n" - + "Restore us, and regain the blissful Seat,\n" - + "Sing Heav'nly Muse, that on the secret top\n" - + "That Shepherd, who first taught the chosen Seed"; - - String actual = grepTool.grep( - "Of", - Collections.singletonList("-v"), - Collections.singletonList("paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, inverted flag") + public void testGreppingASingleFileOneFileSeveralMatchesInvertedFlag() { + assertThat(grepTool.grep( + "Of", + List.of("-v"), + List.of("paradise-lost.txt"))) + .isEqualTo("Brought Death into the World, and all our woe,\n" + + "With loss of Eden, till one greater Man\n" + + "Restore us, and regain the blissful Seat,\n" + + "Sing Heav'nly Muse, that on the secret top\n" + + "That Shepherd, who first taught the chosen Seed"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, no matches, various flags") - public void oneFileNoMatchesVariousFlags() { - String expected = ""; - - String actual = grepTool.grep( - "Gandalf", - Arrays.asList("-n", "-l", "-x", "-i"), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, no matches, various flags") + public void testGreppingASingleFileOneFileNoMatchesVariousFlags() { + assertThat(grepTool.grep( + "Gandalf", + List.of("-n", "-l", "-x", "-i"), + List.of("iliad.txt"))) + .isEqualTo(""); } @Disabled("Remove to run test") @Test - @DisplayName("One file, one match, file flag takes precedence over line flag") - public void oneFileOneMatchFileFlagTakesPrecedenceOverLineFlag() { - String expected = "iliad.txt"; - - String actual = grepTool.grep( - "ten", - Arrays.asList("-n", "-l"), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, one match, file flag takes " + + "precedence over line flag") + public void testGreppingASingleFileOneFileOneMatchFileFlagTakesPrecedenceOver() { + assertThat(grepTool.grep( + "ten", + List.of("-n", "-l"), + List.of("iliad.txt"))) + .isEqualTo("iliad.txt"); } @Disabled("Remove to run test") @Test - @DisplayName("One file, several matches, inverted and match entire lines flags") - public void oneFileSeveralMatchesInvertedAndMatchEntireLinesFlags() { - String expected = "Achilles sing, O Goddess! Peleus' son;\n" - + "His wrath pernicious, who ten thousand woes\n" - + "Caused to Achaia's host, sent many a soul\n" - + "And Heroes gave (so stood the will of Jove)\n" - + "To dogs and to all ravening fowls a prey,\n" - + "When fierce dispute had separated once\n" - + "The noble Chief Achilles from the son\n" - + "Of Atreus, Agamemnon, King of men."; - - String actual = grepTool.grep( - "Illustrious into Ades premature,", - Arrays.asList("-x", "-v"), - Collections.singletonList("iliad.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping a single file -> One file, several matches, inverted and " + + "match entire lines flags") + public void testGreppingASingleFileOneFileSeveralMatchesInvertedAndMatchEntir() { + assertThat(grepTool.grep( + "Illustrious into Ades premature,", + List.of("-x", "-v"), + List.of("iliad.txt"))) + .isEqualTo("Achilles sing, O Goddess! Peleus' son;\n" + + "His wrath pernicious, who ten thousand woes\n" + + "Caused to Achaia's host, sent many a soul\n" + + "And Heroes gave (so stood the will of Jove)\n" + + "To dogs and to all ravening fowls a prey,\n" + + "When fierce dispute had separated once\n" + + "The noble Chief Achilles from the son\n" + + "Of Atreus, Agamemnon, King of men."); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, one match, no flags") - public void multipleFilesOneMatchNoFlags() { - String expected = "iliad.txt:Of Atreus, Agamemnon, King of men."; - - String actual = grepTool.grep( - "Agamemnon", - Collections.emptyList(), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, one match, no flags") + public void testGreppingMultiplesFilesAtOnceMultipleFilesOneMatchNoFlags() { + assertThat(grepTool.grep( + "Agamemnon", + List.of(), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt:Of Atreus, Agamemnon, King of men."); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, no flags") - public void multipleFilesSeveralMatchesNoFlags() { - String expected = "midsummer-night.txt:Nor how it may concern my modesty,\n" - + "midsummer-night.txt:But I beseech your grace that I may know\n" - + "midsummer-night.txt:The worst that may befall me in this case,"; - - String actual = grepTool.grep( - "may", - Collections.emptyList(), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several matches, no flags") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesNoFlag() { + assertThat(grepTool.grep( + "may", + List.of(), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("midsummer-night.txt:Nor how it may concern my modesty,\n" + + "midsummer-night.txt:But I beseech your grace that I may know\n" + + "midsummer-night.txt:The worst that may befall me in this case,"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, print line numbers flag") - public void multipleFilesSeveralMatchesPrintLineNumbersFlag() { - String expected = "midsummer-night.txt:5:But I beseech your grace that I may know\n" - + "midsummer-night.txt:6:The worst that may befall me in this case,\n" - + "paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast\n" - + "paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top"; - - String actual = grepTool.grep( - "that", - Collections.singletonList("-n"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several " + + "matches, print line numbers flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesPrintL() { + assertThat(grepTool.grep( + "that", + List.of("-n"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("midsummer-night.txt:5:But I beseech your grace that I may know\n" + + "midsummer-night.txt:6:The worst that may befall me in this case,\n" + + "paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast\n" + + "paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, one match, print file names flag") - public void multipleFilesOneMatchPrintFileNamesFlag() { - String expected = "iliad.txt\n" - + "paradise-lost.txt"; - - String actual = grepTool.grep( - "who", - Collections.singletonList("-l"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, one match, " + + "print file names flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesOneMatchPrintFileNam() { + assertThat(grepTool.grep( + "who", + List.of("-l"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt\n" + + "paradise-lost.txt"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, case-insensitive flag") - public void multipleFilesSeveralMatchesCaseInsensitiveFlag() { - String expected = "iliad.txt:Caused to Achaia's host, sent many a soul\n" - + "iliad.txt:Illustrious into Ades premature,\n" - + "iliad.txt:And Heroes gave (so stood the will of Jove)\n" - + "iliad.txt:To dogs and to all ravening fowls a prey,\n" - + "midsummer-night.txt:I do entreat your grace to pardon me.\n" - + "midsummer-night.txt:In such a presence here to plead my thoughts;\n" - + "midsummer-night.txt:If I refuse to wed Demetrius.\n" - + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" - + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" - + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top"; - - String actual = grepTool.grep( - "TO", - Collections.singletonList("-i"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several " + + "matches, case-insensitive flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesCaseIn() { + assertThat(grepTool.grep( + "TO", + List.of("-i"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt:Caused to Achaia's host, sent many a soul\n" + + "iliad.txt:Illustrious into Ades premature,\n" + + "iliad.txt:And Heroes gave (so stood the will of Jove)\n" + + "iliad.txt:To dogs and to all ravening fowls a prey,\n" + + "midsummer-night.txt:I do entreat your grace to pardon me.\n" + + "midsummer-night.txt:In such a presence here to plead my thoughts;\n" + + "midsummer-night.txt:If I refuse to wed Demetrius.\n" + + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" + + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" + + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, inverted flag") - public void multipleFilesSeveralMatchesInvertedFlag() { - String expected = "iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" - + "iliad.txt:The noble Chief Achilles from the son\n" - + "midsummer-night.txt:If I refuse to wed Demetrius."; - - String actual = grepTool.grep( - "a", - Collections.singletonList("-v"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several " + + "matches, inverted flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesInvert() { + assertThat(grepTool.grep( + "a", + List.of("-v"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" + + "iliad.txt:The noble Chief Achilles from the son\n" + + "midsummer-night.txt:If I refuse to wed Demetrius."); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, one match, match entire lines flag") - public void multipleFilesOneMatchEntireLinesFlag() { - String expected = "midsummer-night.txt:But I beseech your grace that I may know"; - - String actual = grepTool.grep( - "But I beseech your grace that I may know", - Collections.singletonList("-x"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, one match, " + + "match entire lines flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesOneMatchMatchEntireL() { + assertThat(grepTool.grep( + "But I beseech your grace that I may know", + List.of("-x"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("midsummer-night.txt:But I beseech your grace that I may know"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, one match, multiple flags") - public void multipleFilesOneMatchMultipleFlags() { - String expected = "paradise-lost.txt:4:With loss of Eden, till one greater Man"; - - String actual = grepTool.grep( - "WITH LOSS OF EDEN, TILL ONE GREATER MAN", - Arrays.asList("-n", "-i", "-x"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, one match, multiple flags") + public void testGreppingMultiplesFilesAtOnceMultipleFilesOneMatchMultipleFlag() { + assertThat(grepTool.grep( + "WITH LOSS OF EDEN, TILL ONE GREATER MAN", + List.of("-n", "-i", "-x"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("paradise-lost.txt:4:With loss of Eden, till one greater Man"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, no matches, various flags") - public void multipleFilesNoMatchesVariousFlags() { - String expected = ""; - - String actual = grepTool.grep( - "Frodo", - Arrays.asList("-n", "-l", "-x", "-i"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, no matches, various flags") + public void testGreppingMultiplesFilesAtOnceMultipleFilesNoMatchesVariousFlag() { + assertThat(grepTool.grep( + "Frodo", + List.of("-n", "-l", "-x", "-i"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo(""); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, file flag takes precedence over line number flag") - public void multipleFilesSeveralMatchesFileFlagTakesPrecedenceOverLineNumberFlag() { - String expected = "iliad.txt\n" - + "paradise-lost.txt"; - - String actual = grepTool.grep( - "who", - Arrays.asList("-n", "-l"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several " + + "matches, file flag takes precedence over line number flag") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesFileFl() { + assertThat(grepTool.grep( + "who", + List.of("-n", "-l"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt\n" + + "paradise-lost.txt"); } @Disabled("Remove to run test") @Test - @DisplayName("Multiple files, several matches, inverted and match entire lines flags") - public void multipleFilesSeveralMatchesInvertedAndMatchEntireLinesFlags() { - String expected = "iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" - + "iliad.txt:His wrath pernicious, who ten thousand woes\n" - + "iliad.txt:Caused to Achaia's host, sent many a soul\n" - + "iliad.txt:And Heroes gave (so stood the will of Jove)\n" - + "iliad.txt:To dogs and to all ravening fowls a prey,\n" - + "iliad.txt:When fierce dispute had separated once\n" - + "iliad.txt:The noble Chief Achilles from the son\n" - + "iliad.txt:Of Atreus, Agamemnon, King of men.\n" - + "midsummer-night.txt:I do entreat your grace to pardon me.\n" - + "midsummer-night.txt:I know not by what power I am made bold,\n" - + "midsummer-night.txt:Nor how it may concern my modesty,\n" - + "midsummer-night.txt:In such a presence here to plead my thoughts;\n" - + "midsummer-night.txt:But I beseech your grace that I may know\n" - + "midsummer-night.txt:The worst that may befall me in this case,\n" - + "midsummer-night.txt:If I refuse to wed Demetrius.\n" - + "paradise-lost.txt:Of Mans First Disobedience, and the Fruit\n" - + "paradise-lost.txt:Of that Forbidden Tree, whose mortal tast\n" - + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" - + "paradise-lost.txt:With loss of Eden, till one greater Man\n" - + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" - + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top\n" - + "paradise-lost.txt:Of Oreb, or of Sinai, didst inspire\n" - + "paradise-lost.txt:That Shepherd, who first taught the chosen Seed"; - - String actual = grepTool.grep( - "Illustrious into Ades premature,", - Arrays.asList("-x", "-v"), - Arrays.asList("iliad.txt", "midsummer-night.txt", "paradise-lost.txt") - ); - - assertThat(actual).isEqualTo(expected); + @DisplayName("Test grepping multiples files at once -> Multiple files, several " + + "matches, inverted and match entire lines flags") + public void testGreppingMultiplesFilesAtOnceMultipleFilesSeveralMatchesInvert2() { + assertThat(grepTool.grep( + "Illustrious into Ades premature,", + List.of("-x", "-v"), + List.of("iliad.txt", "midsummer-night.txt", "paradise-lost.txt"))) + .isEqualTo("iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" + + "iliad.txt:His wrath pernicious, who ten thousand woes\n" + + "iliad.txt:Caused to Achaia's host, sent many a soul\n" + + "iliad.txt:And Heroes gave (so stood the will of Jove)\n" + + "iliad.txt:To dogs and to all ravening fowls a prey,\n" + + "iliad.txt:When fierce dispute had separated once\n" + + "iliad.txt:The noble Chief Achilles from the son\n" + + "iliad.txt:Of Atreus, Agamemnon, King of men.\n" + + "midsummer-night.txt:I do entreat your grace to pardon me.\n" + + "midsummer-night.txt:I know not by what power I am made bold,\n" + + "midsummer-night.txt:Nor how it may concern my modesty,\n" + + "midsummer-night.txt:In such a presence here to plead my thoughts;\n" + + "midsummer-night.txt:But I beseech your grace that I may know\n" + + "midsummer-night.txt:The worst that may befall me in this case,\n" + + "midsummer-night.txt:If I refuse to wed Demetrius.\n" + + "paradise-lost.txt:Of Mans First Disobedience, and the Fruit\n" + + "paradise-lost.txt:Of that Forbidden Tree, whose mortal tast\n" + + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" + + "paradise-lost.txt:With loss of Eden, till one greater Man\n" + + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" + + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top\n" + + "paradise-lost.txt:Of Oreb, or of Sinai, didst inspire\n" + + "paradise-lost.txt:That Shepherd, who first taught the chosen Seed"); } private void writeToFile(String filename, List contents) throws IOException { Path file = Paths.get(filename); - Files.write(file, contents, Charset.forName("UTF-8")); + Files.write(file, contents, StandardCharsets.UTF_8); } private void deleteFile(String filename) throws IOException { diff --git a/exercises/practice/hamming/src/test/java/HammingTest.java b/exercises/practice/hamming/src/test/java/HammingTest.java index 26f22491f..ca0243b34 100644 --- a/exercises/practice/hamming/src/test/java/HammingTest.java +++ b/exercises/practice/hamming/src/test/java/HammingTest.java @@ -9,72 +9,95 @@ public class HammingTest { @Test @DisplayName("empty strands") - public void testNoDistanceBetweenEmptyStrands() { - assertThat(new Hamming("", "").getHammingDistance()).isEqualTo(0); + public void emptyStrands() { + + assertThat(new Hamming("", "").getHammingDistance()) + .isEqualTo(0); + } @Disabled("Remove to run test") @Test @DisplayName("single letter identical strands") - public void testNoDistanceBetweenShortIdenticalStrands() { - assertThat(new Hamming("A", "A").getHammingDistance()).isEqualTo(0); + public void singleLetterIdenticalStrands() { + + assertThat(new Hamming("A", "A").getHammingDistance()) + .isEqualTo(0); + } @Disabled("Remove to run test") @Test @DisplayName("single letter different strands") - public void testCompleteDistanceInSingleLetterDifferentStrands() { - assertThat(new Hamming("G", "T").getHammingDistance()).isEqualTo(1); + public void singleLetterDifferentStrands() { + + assertThat(new Hamming("G", "T").getHammingDistance()) + .isEqualTo(1); + } @Disabled("Remove to run test") @Test @DisplayName("long identical strands") - public void testDistanceInLongIdenticalStrands() { - assertThat(new Hamming("GGACTGAAATCTG", "GGACTGAAATCTG").getHammingDistance()).isEqualTo(0); + public void longIdenticalStrands() { + + assertThat(new Hamming("GGACTGAAATCTG", "GGACTGAAATCTG").getHammingDistance()) + .isEqualTo(0); + } @Disabled("Remove to run test") @Test @DisplayName("long different strands") - public void testDistanceInLongDifferentStrands() { - assertThat(new Hamming("GGACGGATTCTG", "AGGACGGATTCT").getHammingDistance()).isEqualTo(9); + public void longDifferentStrands() { + + assertThat(new Hamming("GGACGGATTCTG", "AGGACGGATTCT").getHammingDistance()) + .isEqualTo(9); + } @Disabled("Remove to run test") @Test @DisplayName("disallow first strand longer") - public void testValidatesFirstStrandNotLonger() { + public void disallowFirstStrandLonger() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("AATG", "AAA")) .withMessage("strands must be of equal length"); + } @Disabled("Remove to run test") @Test @DisplayName("disallow second strand longer") - public void testValidatesSecondStrandNotLonger() { + public void disallowSecondStrandLonger() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("ATA", "AGTG")) .withMessage("strands must be of equal length"); + } @Disabled("Remove to run test") @Test - @DisplayName("disallow left empty strand") - public void testDisallowLeftEmptyStrand() { + @DisplayName("disallow empty first strand") + public void disallowEmptyFirstStrand() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("", "G")) .withMessage("strands must be of equal length"); + } @Disabled("Remove to run test") @Test - @DisplayName("disallow right empty strand") - public void testDisallowRightEmptyStrand() { + @DisplayName("disallow empty second strand") + public void disallowEmptySecondStrand() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("G", "")) .withMessage("strands must be of equal length"); + } } diff --git a/exercises/practice/hello-world/src/test/java/GreeterTest.java b/exercises/practice/hello-world/src/test/java/GreeterTest.java index cd5fb79a3..df9f41599 100644 --- a/exercises/practice/hello-world/src/test/java/GreeterTest.java +++ b/exercises/practice/hello-world/src/test/java/GreeterTest.java @@ -7,8 +7,9 @@ public class GreeterTest { @Test @DisplayName("Say Hi!") - public void testThatGreeterReturnsTheCorrectGreeting() { - assertThat(new Greeter().getGreeting()).isEqualTo("Hello, World!"); + public void sayHi() { + assertThat(new Greeter().getGreeting()) + .isEqualTo("Hello, World!"); } } diff --git a/exercises/practice/high-scores/src/test/java/HighScoresTest.java b/exercises/practice/high-scores/src/test/java/HighScoresTest.java index 282d09c6e..7aa6b5d02 100644 --- a/exercises/practice/high-scores/src/test/java/HighScoresTest.java +++ b/exercises/practice/high-scores/src/test/java/HighScoresTest.java @@ -1,109 +1,124 @@ -import java.util.Arrays; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; public class HighScoresTest { @Test @DisplayName("List of scores") - public void shouldReturnListOfScores() { - HighScores highScores = new HighScores(Arrays.asList(30, 50, 20, 70)); - assertThat(highScores.scores()).isEqualTo(Arrays.asList(30, 50, 20, 70)); + public void listOfScores() { + assertThat(new HighScores(List.of(30, 50, 20, 70)).scores()) + .isEqualTo(List.of(30, 50, 20, 70)); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("Latest score") - public void shouldReturnLatestAddedScore() { - HighScores highScores = new HighScores(Arrays.asList(100, 0, 90, 30)); - assertThat(highScores.latest()).isEqualTo(30); + public void latestScore() { + assertThat(new HighScores(List.of(100, 0, 90, 30)).latest()) + .isEqualTo(30); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("Personal best") - public void shouldReturnPersonalBest() { - HighScores highScores = new HighScores(Arrays.asList(40, 100, 70)); - assertThat(highScores.personalBest()).isEqualTo(100); + public void personalBest() { + assertThat(new HighScores(List.of(40, 100, 70)).personalBest()) + .isEqualTo(100); } - @Test @Disabled("Remove to run test") - @DisplayName("Personal top three from a list of scores") - public void shouldReturnPersonalTopThreeFromListOfScores() { - HighScores highScores = new HighScores(Arrays.asList(10, 30, 90, 30, 100, 20, 10, 0, 30, 40, 40, 70, 70)); - assertThat(highScores.personalTopThree()).isEqualTo(Arrays.asList(100, 90, 70)); + @Test + @DisplayName("Top 3 scores -> Personal top three from a list of scores") + public void top3ScoresPersonalTopThreeFromAListOfScores() { + assertThat(new HighScores(List.of( + 10, + 30, + 90, + 30, + 100, + 20, + 10, + 0, + 30, + 40, + 40, + 70, + 70 + )).personalTopThree()) + .isEqualTo(List.of(100, 90, 70)); } - @Test @Disabled("Remove to run test") - @DisplayName("Personal top highest to lowest") - public void shouldReturnPersonalTopThreeSortedHighestToLowest() { - HighScores highScores = new HighScores(Arrays.asList(20, 10, 30)); - assertThat(highScores.personalTopThree()).isEqualTo(Arrays.asList(30, 20, 10)); + @Test + @DisplayName("Top 3 scores -> Personal top highest to lowest") + public void top3ScoresPersonalTopHighestToLowest() { + assertThat(new HighScores(List.of(20, 10, 30)).personalTopThree()) + .isEqualTo(List.of(30, 20, 10)); } - @Test @Disabled("Remove to run test") - @DisplayName("Personal top when there is a tie") - public void shouldReturnPersonalTopThreeWhenThereIsATie() { - HighScores highScores = new HighScores(Arrays.asList(40, 20, 40, 30)); - assertThat(highScores.personalTopThree()).isEqualTo(Arrays.asList(40, 40, 30)); + @Test + @DisplayName("Top 3 scores -> Personal top when there is a tie") + public void top3ScoresPersonalTopWhenThereIsATie() { + assertThat(new HighScores(List.of(40, 20, 40, 30)).personalTopThree()) + .isEqualTo(List.of(40, 40, 30)); } - @Test @Disabled("Remove to run test") - @DisplayName("Personal top when there are less than 3") - public void shouldReturnPersonalTopWhenThereIsLessThanThreeScores() { - HighScores highScores = new HighScores(Arrays.asList(30, 70)); - assertThat(highScores.personalTopThree()).isEqualTo(Arrays.asList(70, 30)); + @Test + @DisplayName("Top 3 scores -> Personal top when there are less than 3") + public void top3ScoresPersonalTopWhenThereAreLessThan3() { + assertThat(new HighScores(List.of(30, 70)).personalTopThree()) + .isEqualTo(List.of(70, 30)); } - @Test @Disabled("Remove to run test") - @DisplayName("Personal top when there is only one") - public void shouldReturnPersonalTopWhenThereIsOnlyOneScore() { - HighScores highScores = new HighScores(Arrays.asList(40)); - assertThat(highScores.personalTopThree()).isEqualTo(Arrays.asList(40)); + @Test + @DisplayName("Top 3 scores -> Personal top when there is only one") + public void top3ScoresPersonalTopWhenThereIsOnlyOne() { + assertThat(new HighScores(List.of(40)).personalTopThree()) + .isEqualTo(List.of(40)); } - @Test @Disabled("Remove to run test") - @DisplayName("Latest score after personal top scores") - public void callingLatestAfterPersonalTopThree() { - HighScores highScores = new HighScores(Arrays.asList(70, 50, 20, 30)); + @Test + @DisplayName("Top 3 scores -> Latest score after personal top scores") + public void top3ScoresLatestScoreAfterPersonalTopScores() { + HighScores highScores = new HighScores(List.of(70, 50, 20, 30)); highScores.personalTopThree(); assertThat(highScores.latest()).isEqualTo(30); } - @Test @Disabled("Remove to run test") - @DisplayName("Scores after personal top scores") - public void callingScoresAfterPersonalTopThree() { - HighScores highScores = new HighScores(Arrays.asList(30, 50, 20, 70)); + @Test + @DisplayName("Top 3 scores -> Scores after personal top scores") + public void top3ScoresScoresAfterPersonalTopScores() { + HighScores highScores = new HighScores(List.of(30, 50, 20, 70)); highScores.personalTopThree(); - assertThat(highScores.scores()).isEqualTo(Arrays.asList(30, 50, 20, 70)); + assertThat(highScores.scores()).isEqualTo(List.of(30, 50, 20, 70)); } - @Test @Disabled("Remove to run test") - @DisplayName("Latest score after personal best") - public void callingLatestAfterPersonalBest() { - HighScores highScores = new HighScores(Arrays.asList(20, 70, 15, 25, 30)); + @Test + @DisplayName("Top 3 scores -> Latest score after personal best") + public void top3ScoresLatestScoreAfterPersonalBest() { + HighScores highScores = new HighScores(List.of(20, 70, 15, 25, 30)); highScores.personalBest(); assertThat(highScores.latest()).isEqualTo(30); } - @Test @Disabled("Remove to run test") - @DisplayName("Scores after personal best") - public void callingScoresAfterPersonalBest() { - HighScores highScores = new HighScores(Arrays.asList(20, 70, 15, 25, 30)); + @Test + @DisplayName("Top 3 scores -> Scores after personal best") + public void top3ScoresScoresAfterPersonalBest() { + HighScores highScores = new HighScores(List.of(20, 70, 15, 25, 30)); highScores.personalBest(); - assertThat(highScores.scores()).isEqualTo(Arrays.asList(20, 70, 15, 25, 30)); + assertThat(highScores.scores()).isEqualTo(List.of(20, 70, 15, 25, 30)); } + } diff --git a/exercises/practice/house/src/test/java/HouseTest.java b/exercises/practice/house/src/test/java/HouseTest.java index 4841a9d14..30736aef7 100644 --- a/exercises/practice/house/src/test/java/HouseTest.java +++ b/exercises/practice/house/src/test/java/HouseTest.java @@ -1,303 +1,245 @@ -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class HouseTest { - private House house; - - @BeforeEach - public void setup() { - house = new House(); - } + private House house = new House(); @Test @DisplayName("verse one - the house that jack built") - public void verseOne() { - assertThat(house.verse(1)).isEqualTo( - "This is the house that Jack built."); + public void verseOneTheHouseThatJackBuilt() { + + assertThat(house.verse(1)) + .isEqualTo("This is the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse two - the malt that lay") - public void verseTwo() { - assertThat(house.verse(2)).isEqualTo( - "This is the malt " + - "that lay in the house that Jack built." - ); + public void verseTwoTheMaltThatLay() { + + assertThat(house.verse(2)) + .isEqualTo("This is the malt that lay in the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse three - the rat that ate") - public void verseThree() { - assertThat(house.verse(3)).isEqualTo( - "This is the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseThreeTheRatThatAte() { + + assertThat(house.verse(3)) + .isEqualTo("This is the rat that ate the malt that lay in the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse four - the cat that killed") - public void verseFour() { - assertThat(house.verse(4)).isEqualTo( - "This is the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseFourTheCatThatKilled() { + + assertThat(house.verse(4)) + .isEqualTo("This is the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse five - the dog that worried") - public void verseFive() { - assertThat(house.verse(5)).isEqualTo( - "This is the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseFiveTheDogThatWorried() { + + assertThat(house.verse(5)) + .isEqualTo("This is the dog that worried the cat that killed the rat that ate the " + + "malt that lay in the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse six - the cow with the crumpled horn") - public void verseSix() { - assertThat(house.verse(6)).isEqualTo( - "This is the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseSixTheCowWithTheCrumpledHorn() { + + assertThat(house.verse(6)) + .isEqualTo("This is the cow with the crumpled horn that tossed the dog that " + + "worried the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse seven - the maiden all forlorn") - public void verseSeven() { - assertThat(house.verse(7)).isEqualTo( - "This is the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseSevenTheMaidenAllForlorn() { + + assertThat(house.verse(7)) + .isEqualTo("This is the maiden all forlorn that milked the cow with the crumpled " + + "horn that tossed the dog that worried the cat that killed the rat that " + + "ate the malt that lay in the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse eight - the man all tattered and torn") - public void verseEight() { - assertThat(house.verse(8)).isEqualTo( - "This is the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseEightTheManAllTatteredAndTorn() { + + assertThat(house.verse(8)) + .isEqualTo("This is the man all tattered and torn that kissed the maiden all " + + "forlorn that milked the cow with the crumpled horn that tossed the dog " + + "that worried the cat that killed the rat that ate the malt that lay in " + + "the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse nine - the priest all shaven and shorn") - public void verseNine() { - assertThat(house.verse(9)).isEqualTo( - "This is the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verseNineThePriestAllShavenAndShorn() { + + assertThat(house.verse(9)) + .isEqualTo("This is the priest all shaven and shorn that married the man all " + + "tattered and torn that kissed the maiden all forlorn that milked the " + + "cow with the crumpled horn that tossed the dog that worried the cat " + + "that killed the rat that ate the malt that lay in the house that Jack " + + "built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse 10 - the rooster that crowed in the morn") - public void verse10() { - assertThat(house.verse(10)).isEqualTo( - "This is the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verse10TheRoosterThatCrowedInTheMorn() { + + assertThat(house.verse(10)) + .isEqualTo("This is the rooster that crowed in the morn that woke the priest all " + + "shaven and shorn that married the man all tattered and torn that " + + "kissed the maiden all forlorn that milked the cow with the crumpled " + + "horn that tossed the dog that worried the cat that killed the rat that " + + "ate the malt that lay in the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse 11 - the farmer sowing his corn") - public void verse11() { - assertThat(house.verse(11)).isEqualTo( - "This is the farmer sowing his corn " + - "that kept the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verse11TheFarmerSowingHisCorn() { + + assertThat(house.verse(11)) + .isEqualTo("This is the farmer sowing his corn that kept the rooster that crowed " + + "in the morn that woke the priest all shaven and shorn that married the " + + "man all tattered and torn that kissed the maiden all forlorn that " + + "milked the cow with the crumpled horn that tossed the dog that worried " + + "the cat that killed the rat that ate the malt that lay in the house " + + "that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("verse 12 - the horse and the hound and the horn") - public void verse12() { - assertThat(house.verse(12)).isEqualTo( - "This is the horse and the hound and the horn " + - "that belonged to the farmer sowing his corn " + - "that kept the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void verse12TheHorseAndTheHoundAndTheHorn() { + + assertThat(house.verse(12)) + .isEqualTo("This is the horse and the hound and the horn that belonged to the " + + "farmer sowing his corn that kept the rooster that crowed in the morn " + + "that woke the priest all shaven and shorn that married the man all " + + "tattered and torn that kissed the maiden all forlorn that milked the " + + "cow with the crumpled horn that tossed the dog that worried the cat " + + "that killed the rat that ate the malt that lay in the house that Jack " + + "built."); + } @Disabled("Remove to run test") @Test @DisplayName("multiple verses") public void multipleVerses() { - int startVerse = 4; - int endVerse = 8; - - assertThat(house.verses(startVerse, endVerse)).isEqualTo( - "This is the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + + assertThat(house.verses(4, 8)) + .isEqualTo("This is the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built." + + "\n" + + "This is the dog that worried the cat that killed the rat that ate the " + + "malt that lay in the house that Jack built." + + "\n" + + "This is the cow with the crumpled horn that tossed the dog that " + + "worried the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built." + + "\n" + + "This is the maiden all forlorn that milked the cow with the crumpled " + + "horn that tossed the dog that worried the cat that killed the rat that " + + "ate the malt that lay in the house that Jack built." + + "\n" + + "This is the man all tattered and torn that kissed the maiden all " + + "forlorn that milked the cow with the crumpled horn that tossed the dog " + + "that worried the cat that killed the rat that ate the malt that lay in " + + "the house that Jack built."); + } @Disabled("Remove to run test") @Test @DisplayName("full rhyme") - public void wholeRhyme() { - assertThat(house.sing()).isEqualTo( - "This is the house that Jack built.\n" + - "This is the malt " + - "that lay in the house that Jack built.\n" + - "This is the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the farmer sowing his corn " + - "that kept the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built.\n" + - "This is the horse and the hound and the horn " + - "that belonged to the farmer sowing his corn " + - "that kept the rooster that crowed in the morn " + - "that woke the priest all shaven and shorn " + - "that married the man all tattered and torn " + - "that kissed the maiden all forlorn " + - "that milked the cow with the crumpled horn " + - "that tossed the dog " + - "that worried the cat " + - "that killed the rat " + - "that ate the malt " + - "that lay in the house that Jack built."); + public void fullRhyme() { + + assertThat(house.sing()) + .isEqualTo("This is the house that Jack built." + + "\n" + + "This is the malt that lay in the house that Jack built." + + "\n" + + "This is the rat that ate the malt that lay in the house that Jack built." + + "\n" + + "This is the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built." + + "\n" + + "This is the dog that worried the cat that killed the rat that ate the " + + "malt that lay in the house that Jack built." + + "\n" + + "This is the cow with the crumpled horn that tossed the dog that " + + "worried the cat that killed the rat that ate the malt that lay in the " + + "house that Jack built." + + "\n" + + "This is the maiden all forlorn that milked the cow with the crumpled " + + "horn that tossed the dog that worried the cat that killed the rat that " + + "ate the malt that lay in the house that Jack built." + + "\n" + + "This is the man all tattered and torn that kissed the maiden all " + + "forlorn that milked the cow with the crumpled horn that tossed the dog " + + "that worried the cat that killed the rat that ate the malt that lay in " + + "the house that Jack built." + + "\n" + + "This is the priest all shaven and shorn that married the man all " + + "tattered and torn that kissed the maiden all forlorn that milked the " + + "cow with the crumpled horn that tossed the dog that worried the cat " + + "that killed the rat that ate the malt that lay in the house that Jack " + + "built." + + "\n" + + "This is the rooster that crowed in the morn that woke the priest all " + + "shaven and shorn that married the man all tattered and torn that " + + "kissed the maiden all forlorn that milked the cow with the crumpled " + + "horn that tossed the dog that worried the cat that killed the rat that " + + "ate the malt that lay in the house that Jack built." + + "\n" + + "This is the farmer sowing his corn that kept the rooster that crowed " + + "in the morn that woke the priest all shaven and shorn that married the " + + "man all tattered and torn that kissed the maiden all forlorn that " + + "milked the cow with the crumpled horn that tossed the dog that worried " + + "the cat that killed the rat that ate the malt that lay in the house " + + "that Jack built." + + "\n" + + "This is the horse and the hound and the horn that belonged to the " + + "farmer sowing his corn that kept the rooster that crowed in the morn " + + "that woke the priest all shaven and shorn that married the man all " + + "tattered and torn that kissed the maiden all forlorn that milked the " + + "cow with the crumpled horn that tossed the dog that worried the cat " + + "that killed the rat that ate the malt that lay in the house that Jack " + + "built."); + } + } diff --git a/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java b/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java index 9c26e13e5..755c17409 100644 --- a/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java +++ b/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java @@ -1,277 +1,345 @@ -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class IntergalacticTransmissionTest { @Test - @DisplayName("calculate transmit sequences") + @DisplayName("calculate transmit sequences -> empty message") public void calculateTransmitSequencesEmptyMessage() { + List input = List.of(); List expected = List.of(); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x00 is transmitted as 0x0000") + @DisplayName("calculate transmit sequences -> 0x00 is transmitted as 0x0000") public void calculateTransmitSequences0x00IsTransmittedAs0x0000() { + List input = List.of(0x00); List expected = List.of(0x00, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x02 is transmitted as 0x0300") + @DisplayName("calculate transmit sequences -> 0x02 is transmitted as 0x0300") public void calculateTransmitSequences0x02IsTransmittedAs0x0300() { + List input = List.of(0x02); List expected = List.of(0x03, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x06 is transmitted as 0x0600") + @DisplayName("calculate transmit sequences -> 0x06 is transmitted as 0x0600") public void calculateTransmitSequences0x06IsTransmittedAs0x0600() { + List input = List.of(0x06); List expected = List.of(0x06, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x05 is transmitted as 0x0581") + @DisplayName("calculate transmit sequences -> 0x05 is transmitted as 0x0581") public void calculateTransmitSequences0x05IsTransmittedAs0x0581() { + List input = List.of(0x05); List expected = List.of(0x05, 0x81); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x29 is transmitted as 0x2881") + @DisplayName("calculate transmit sequences -> 0x29 is transmitted as 0x2881") public void calculateTransmitSequences0x29IsTransmittedAs0x2881() { + List input = List.of(0x29); List expected = List.of(0x28, 0x81); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0xc001c0de is transmitted as 0xc000711be1") + @DisplayName("calculate transmit sequences -> 0xc001c0de is transmitted as 0xc000711be1") public void calculateTransmitSequences0xc001c0deIsTransmittedAs0xc000711be1() { + List input = List.of(0xc0, 0x01, 0xc0, 0xde); List expected = List.of(0xc0, 0x00, 0x71, 0x1b, 0xe1); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("six byte message") + @DisplayName("calculate transmit sequences -> six byte message") public void calculateTransmitSequencesSixByteMessage() { + List input = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x21); List expected = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0x84); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("at 7 bytes long, no padding is required") + @DisplayName("calculate transmit sequences -> seven byte message") public void calculateTransmitSequencesSevenByteMessage() { + List input = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x31, 0x21); List expected = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x42); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("eight byte message") + @DisplayName("calculate transmit sequences -> eight byte message") public void calculateTransmitSequencesEightByteMessage() { + List input = List.of(0xc0, 0x01, 0x13, 0x37, 0xc0, 0xde, 0x21, 0x21); - List expected = List.of(0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, 0x21, 0x81); + List expected = List.of( + 0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, + 0x21, 0x81 + ); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("twenty byte message") + @DisplayName("calculate transmit sequences -> twenty byte message") public void calculateTransmitSequencesTwentyByteMessage() { + List input = List.of( - 0x45, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x6d, 0x20, 0x69, - 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65, 0x21); + 0x45, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x6d, + 0x20, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, + 0x6f, 0x6d, 0x65, 0x21 + ); List expected = List.of( - 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, 0x6c, 0x90, - 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xee, 0x65, 0xb8, 0xdb, 0xed, - 0xd7, 0x28, 0x84); + 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, + 0x6c, 0x90, 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xee, + 0x65, 0xb8, 0xdb, 0xed, 0xd7, 0x28, 0x84 + ); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("empty message") + @DisplayName("decode received messages -> empty message") public void decodeReceivedMessagesEmptyMessage() { + List input = List.of(); List expected = List.of(); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("zero message") + @DisplayName("decode received messages -> zero message") public void decodeReceivedMessagesZeroMessage() { + List input = List.of(0x00, 0x00); List expected = List.of(0x00); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x0300 is decoded to 0x02") + @DisplayName("decode received messages -> 0x0300 is decoded to 0x02") public void decodeReceivedMessages0x0300IsDecodedTo0x02() { + List input = List.of(0x03, 0x00); List expected = List.of(0x02); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x0581 is decoded to 0x05") + @DisplayName("decode received messages -> 0x0581 is decoded to 0x05") public void decodeReceivedMessages0x0581IsDecodedTo0x05() { + List input = List.of(0x05, 0x81); List expected = List.of(0x05); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0x2881 is decoded to 0x29") + @DisplayName("decode received messages -> 0x2881 is decoded to 0x29") public void decodeReceivedMessages0x2881IsDecodedTo0x29() { + List input = List.of(0x28, 0x81); List expected = List.of(0x29); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("first byte has wrong parity") - public void decodeFirstByteWrongParity() { + @DisplayName("decode received messages -> first byte has wrong parity") + public void decodeReceivedMessagesFirstByteHasWrongParity() { + List input = List.of(0x07, 0x00); - assertThrows(IllegalArgumentException.class, () - -> IntergalacticTransmission.decodeSequence(input)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); + } @Disabled("Remove to run test") @Test - @DisplayName("second byte has wrong parity") - public void decodeSecondByteWrongParity() { + @DisplayName("decode received messages -> second byte has wrong parity") + public void decodeReceivedMessagesSecondByteHasWrongParity() { + List input = List.of(0x03, 0x68); - assertThrows(IllegalArgumentException.class, () - -> IntergalacticTransmission.decodeSequence(input)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); + } @Disabled("Remove to run test") @Test - @DisplayName("0xcf4b00 is decoded to 0xce94") - public void decode0xcf4b00To0xce94() { + @DisplayName("decode received messages -> 0xcf4b00 is decoded to 0xce94") + public void decodeReceivedMessages0xcf4b00IsDecodedTo0xce94() { + List input = List.of(0xcf, 0x4b, 0x00); List expected = List.of(0xce, 0x94); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("0xe2566500 is decoded to 0xe2ad90") - public void decode0xe2566500To0xe2ad90() { + @DisplayName("decode received messages -> 0xe2566500 is decoded to 0xe2ad90") + public void decodeReceivedMessages0xe2566500IsDecodedTo0xe2ad90() { + List input = List.of(0xe2, 0x56, 0x65, 0x00); List expected = List.of(0xe2, 0xad, 0x90); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("six byte message") - public void decodeSixByteMessage() { + @DisplayName("decode received messages -> six byte message") + public void decodeReceivedMessagesSixByteMessage() { + List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0x84); List expected = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("seven byte message") - public void decodeSevenByteMessage() { + @DisplayName("decode received messages -> seven byte message") + public void decodeReceivedMessagesSevenByteMessage() { + List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x42); List expected = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x31, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("last byte has wrong parity") - public void decodeLastByteWrongParity() { + @DisplayName("decode received messages -> last byte has wrong parity") + public void decodeReceivedMessagesLastByteHasWrongParity() { + List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x43); - assertThrows(IllegalArgumentException.class, () - -> IntergalacticTransmission.decodeSequence(input)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); + } @Disabled("Remove to run test") @Test - @DisplayName("eight byte message") - public void decodeEightByteMessage() { - List input = List.of(0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, 0x21, 0x81); + @DisplayName("decode received messages -> eight byte message") + public void decodeReceivedMessagesEightByteMessage() { + + List input = List.of( + 0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, + 0x21, 0x81 + ); List expected = List.of(0xc0, 0x01, 0x13, 0x37, 0xc0, 0xde, 0x21, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("twenty byte message") - public void decodeTwentyByteMessage() { + @DisplayName("decode received messages -> twenty byte message") + public void decodeReceivedMessagesTwentyByteMessage() { + List input = List.of( - 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, 0x6c, 0x90, 0x1b, - 0x2e, 0x33, 0x03, 0x84, 0xee, 0x65, 0xb8, 0xdb, 0xed, 0xd7, 0x28, 0x84); + 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, + 0x6c, 0x90, 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xee, + 0x65, 0xb8, 0xdb, 0xed, 0xd7, 0x28, 0x84 + ); List expected = List.of( - 0x45, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x6d, 0x20, 0x69, - 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65, 0x21); + 0x45, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x6d, + 0x20, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, + 0x6f, 0x6d, 0x65, 0x21 + ); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); + } @Disabled("Remove to run test") @Test - @DisplayName("wrong parity on 16th byte") - public void decodeWrongParityOn16thByte() { + @DisplayName("decode received messages -> wrong parity on 16th byte") + public void decodeReceivedMessagesWrongParityOn16thByte() { + List input = List.of( - 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, 0x6c, 0x90, - 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xef, 0x65, 0xb8, 0xdb, 0xed, 0xd7, 0x28, 0x84); - assertThrows(IllegalArgumentException.class, () - -> IntergalacticTransmission.decodeSequence(input)); + 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, + 0x6c, 0x90, 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xef, + 0x65, 0xb8, 0xdb, 0xed, 0xd7, 0x28, 0x84 + ); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); + } + } diff --git a/exercises/practice/isbn-verifier/src/test/java/IsbnVerifierTest.java b/exercises/practice/isbn-verifier/src/test/java/IsbnVerifierTest.java index 2848b63c5..a1c82d2df 100644 --- a/exercises/practice/isbn-verifier/src/test/java/IsbnVerifierTest.java +++ b/exercises/practice/isbn-verifier/src/test/java/IsbnVerifierTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,163 +5,156 @@ import static org.assertj.core.api.Assertions.assertThat; public class IsbnVerifierTest { - private IsbnVerifier isbnVerifier; - - @BeforeEach - public void setUp() { - isbnVerifier = new IsbnVerifier(); - } @Test @DisplayName("valid isbn") - public void validIsbnNumber() { - assertThat(isbnVerifier.isValid("3-598-21508-8")).isTrue(); + public void validIsbn() { + assertThat(new IsbnVerifier().isValid("3-598-21508-8")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("invalid isbn check digit") public void invalidIsbnCheckDigit() { - assertThat(isbnVerifier.isValid("3-598-21508-9")).isFalse(); + assertThat(new IsbnVerifier().isValid("3-598-21508-9")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("valid isbn with a check digit of 10") - public void validIsbnNumberWithCheckDigitOfTen() { - assertThat(isbnVerifier.isValid("3-598-21507-X")).isTrue(); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("valid isbn with check digit padded with letters is invalid") - public void validIsbnNumberWithCheckDigitPaddedWithLettersIsInvalid() { - assertThat(isbnVerifier.isValid("ABCDEFG3-598-21507-XQWERTYUI")).isFalse(); + public void validIsbnWithACheckDigitOf10() { + assertThat(new IsbnVerifier().isValid("3-598-21507-X")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("check digit is a character other than X") public void checkDigitIsACharacterOtherThanX() { - assertThat(isbnVerifier.isValid("3-598-21507-A")).isFalse(); + assertThat(new IsbnVerifier().isValid("3-598-21507-A")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid check digit in isbn is not treated as zero") - public void invalidCheckDigitInIsbn() { - assertThat(isbnVerifier.isValid("4-598-21507-B")).isFalse(); + public void invalidCheckDigitInIsbnIsNotTreatedAsZero() { + assertThat(new IsbnVerifier().isValid("4-598-21507-B")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid character in isbn is not treated as zero") - public void invalidCharacterInIsbn() { - assertThat(isbnVerifier.isValid("3-598-P1581-X")).isFalse(); + public void invalidCharacterInIsbnIsNotTreatedAsZero() { + assertThat(new IsbnVerifier().isValid("3-598-P1581-X")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("X is only valid as a check digit") public void xIsOnlyValidAsACheckDigit() { - assertThat(isbnVerifier.isValid("3-598-2X507-9")).isFalse(); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("only one check digit is allowed") - public void onlyOneCheckDigitIsAllowed() { - assertThat(isbnVerifier.isValid("3-598-21508-96")).isFalse(); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("X is not substituted by the value 10") - public void xIsNotSubstitutedByTheValue10() { - assertThat(isbnVerifier.isValid("3-598-2X507-5")).isFalse(); + assertThat(new IsbnVerifier().isValid("3-598-2X507-9")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("valid isbn without separating dashes") public void validIsbnWithoutSeparatingDashes() { - assertThat(isbnVerifier.isValid("3598215088")).isTrue(); + assertThat(new IsbnVerifier().isValid("3598215088")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("isbn without separating dashes and X as check digit") public void isbnWithoutSeparatingDashesAndXAsCheckDigit() { - assertThat(isbnVerifier.isValid("359821507X")).isTrue(); + assertThat(new IsbnVerifier().isValid("359821507X")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("isbn without check digit and dashes") public void isbnWithoutCheckDigitAndDashes() { - assertThat(isbnVerifier.isValid("359821507")).isFalse(); + assertThat(new IsbnVerifier().isValid("359821507")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("too long isbn and no dashes") public void tooLongIsbnAndNoDashes() { - assertThat(isbnVerifier.isValid("3598215078X")).isFalse(); + assertThat(new IsbnVerifier().isValid("3598215078X")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("too short isbn") public void tooShortIsbn() { - assertThat(isbnVerifier.isValid("00")).isFalse(); + assertThat(new IsbnVerifier().isValid("00")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("isbn without check digit") public void isbnWithoutCheckDigit() { - assertThat(isbnVerifier.isValid("3-598-21507")).isFalse(); + assertThat(new IsbnVerifier().isValid("3-598-21507")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("check digit of X should not be used for 0") - public void checkDigitOfXShouldNotBeUsedForZero() { - assertThat(isbnVerifier.isValid("3-598-21515-X")).isFalse(); + public void checkDigitOfXShouldNotBeUsedFor0() { + assertThat(new IsbnVerifier().isValid("3-598-21515-X")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("empty isbn") public void emptyIsbn() { - assertThat(isbnVerifier.isValid("")).isFalse(); + assertThat(new IsbnVerifier().isValid("")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("input is 9 characters") - public void inputIsNineCharacters() { - assertThat(isbnVerifier.isValid("134456729")).isFalse(); + public void inputIs9Characters() { + assertThat(new IsbnVerifier().isValid("134456729")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid characters are not ignored after checking length") public void invalidCharactersAreNotIgnoredAfterCheckingLength() { - assertThat(isbnVerifier.isValid("3132P34035")).isFalse(); + assertThat(new IsbnVerifier().isValid("3132P34035")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid characters are not ignored before checking length") public void invalidCharactersAreNotIgnoredBeforeCheckingLength() { - assertThat(isbnVerifier.isValid("3598P215088")).isFalse(); + assertThat(new IsbnVerifier().isValid("3598P215088")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("input is too long but contains a valid isbn") public void inputIsTooLongButContainsAValidIsbn() { - assertThat(isbnVerifier.isValid("98245726788")).isFalse(); + assertThat(new IsbnVerifier().isValid("98245726788")) + .isFalse(); } + } diff --git a/exercises/practice/isogram/src/test/java/IsogramCheckerTest.java b/exercises/practice/isogram/src/test/java/IsogramCheckerTest.java index cdc73f73c..e6731b94b 100644 --- a/exercises/practice/isogram/src/test/java/IsogramCheckerTest.java +++ b/exercises/practice/isogram/src/test/java/IsogramCheckerTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,107 +5,116 @@ import static org.assertj.core.api.Assertions.assertThat; public class IsogramCheckerTest { - private IsogramChecker isogramChecker; - - @BeforeEach - public void setUp() { - isogramChecker = new IsogramChecker(); - } @Test @DisplayName("empty string") - public void testEmptyString() { - assertThat(isogramChecker.isIsogram("")).isTrue(); + public void emptyString() { + assertThat(new IsogramChecker().isIsogram("")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("isogram with only lower case characters") - public void testLowercaseIsogram() { - assertThat(isogramChecker.isIsogram("isogram")).isTrue(); + public void isogramWithOnlyLowerCaseCharacters() { + assertThat(new IsogramChecker().isIsogram("isogram")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("word with one duplicated character") - public void testNotIsogram() { - assertThat(isogramChecker.isIsogram("eleven")).isFalse(); + public void wordWithOneDuplicatedCharacter() { + assertThat(new IsogramChecker().isIsogram("eleven")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("word with one duplicated character from the end of the alphabet") - public void testDuplicateEndAlphabet() { - assertThat(isogramChecker.isIsogram("zzyzx")).isFalse(); + public void wordWithOneDuplicatedCharacterFromTheEndOfTheAlphabet() { + assertThat(new IsogramChecker().isIsogram("zzyzx")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("longest reported english isogram") - public void testMediumLongIsogram() { - assertThat(isogramChecker.isIsogram("subdermatoglyphic")).isTrue(); + public void longestReportedEnglishIsogram() { + assertThat(new IsogramChecker().isIsogram("subdermatoglyphic")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("word with duplicated character in mixed case") - public void testCaseInsensitive() { - assertThat(isogramChecker.isIsogram("Alphabet")).isFalse(); + public void wordWithDuplicatedCharacterInMixedCase() { + assertThat(new IsogramChecker().isIsogram("Alphabet")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("word with duplicated character in mixed case, lowercase first") - public void testDuplicateMixedCase() { - assertThat(isogramChecker.isIsogram("alphAbet")).isFalse(); + public void wordWithDuplicatedCharacterInMixedCaseLowercaseFirst() { + assertThat(new IsogramChecker().isIsogram("alphAbet")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("hypothetical isogrammic word with hyphen") - public void testIsogramWithHyphen() { - assertThat(isogramChecker.isIsogram("thumbscrew-japingly")).isTrue(); + public void hypotheticalIsogrammicWordWithHyphen() { + assertThat(new IsogramChecker().isIsogram("thumbscrew-japingly")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("hypothetical word with duplicated character following hyphen") - public void testIsogramWithDuplicatedCharAfterHyphen() { - assertThat(isogramChecker.isIsogram("thumbscrew-jappingly")).isFalse(); + public void hypotheticalWordWithDuplicatedCharacterFollowingHyphen() { + assertThat(new IsogramChecker().isIsogram("thumbscrew-jappingly")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("isogram with duplicated hyphen") - public void testIsogramWithDuplicatedHyphen() { - assertThat(isogramChecker.isIsogram("six-year-old")).isTrue(); + public void isogramWithDuplicatedHyphen() { + assertThat(new IsogramChecker().isIsogram("six-year-old")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("made-up name that is an isogram") - public void testMadeUpNameThatIsAnIsogram() { - assertThat(isogramChecker.isIsogram("Emily Jung Schwartzkopf")).isTrue(); + public void madeUpNameThatIsAnIsogram() { + assertThat(new IsogramChecker().isIsogram("Emily Jung Schwartzkopf")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("duplicated character in the middle") - public void testDuplicatedCharacterInTheMiddleIsNotIsogram() { - assertThat(isogramChecker.isIsogram("accentor")).isFalse(); + public void duplicatedCharacterInTheMiddle() { + assertThat(new IsogramChecker().isIsogram("accentor")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("same first and last characters") - public void testSameFirstAndLast() { - assertThat(new IsogramChecker().isIsogram("angola")).isFalse(); + public void sameFirstAndLastCharacters() { + assertThat(new IsogramChecker().isIsogram("angola")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("word with duplicated character and with two hyphens") - public void testDuplicatedCharacterAndTwoHyphens() { - assertThat(new IsogramChecker().isIsogram("up-to-date")).isFalse(); + public void wordWithDuplicatedCharacterAndWithTwoHyphens() { + assertThat(new IsogramChecker().isIsogram("up-to-date")) + .isFalse(); } + } diff --git a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java index c515bf8bc..764df1b7f 100644 --- a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java +++ b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,60 +8,167 @@ public class KillerSudokuHelperTest { - private KillerSudokuHelper helper; + private KillerSudokuHelper helper = new KillerSudokuHelper(); + + @Test + @DisplayName("Trivial 1-digit cages -> 1") + public void trivial1DigitCages1() { + + assertThat(helper.combinationsInCage( + 1, + 1)) + .isEqualTo(List.of(List.of(1))); - @BeforeEach - void setUp() { - helper = new KillerSudokuHelper(); } + @Disabled("Remove to run test") @Test - @DisplayName("Trivial 1-digit cages -> 1 to 9") - public void testTrivialOneDigitCages() { - for (int n = 1; n <= 9; n++) { - List> expected = List.of(List.of(n)); - assertThat(helper.combinationsInCage(n, 1)).isEqualTo(expected); - } + @DisplayName("Trivial 1-digit cages -> 2") + public void trivial1DigitCages2() { + + assertThat(helper.combinationsInCage( + 2, + 1)) + .isEqualTo(List.of(List.of(2))); + } + @Disabled("Remove to run test") @Test + @DisplayName("Trivial 1-digit cages -> 3") + public void trivial1DigitCages3() { + + assertThat(helper.combinationsInCage( + 3, + 1)) + .isEqualTo(List.of(List.of(3))); + + } + @Disabled("Remove to run test") - @DisplayName("Cage with sum 45 contains all digits 1:9") - public void testCageWithSum45ContainsAllDigits() { - List> expected = List.of(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9)); - assertThat(helper.combinationsInCage(45, 9)).isEqualTo(expected); + @Test + @DisplayName("Trivial 1-digit cages -> 4") + public void trivial1DigitCages4() { + + assertThat(helper.combinationsInCage( + 4, + 1)) + .isEqualTo(List.of(List.of(4))); + } + @Disabled("Remove to run test") @Test + @DisplayName("Trivial 1-digit cages -> 5") + public void trivial1DigitCages5() { + + assertThat(helper.combinationsInCage( + 5, + 1)) + .isEqualTo(List.of(List.of(5))); + + } + @Disabled("Remove to run test") - @DisplayName("Cage with only 1 possible combination") - public void testCageWithOnlyOnePossibleCombination() { - List> expected = List.of(List.of(1, 2, 4)); - assertThat(helper.combinationsInCage(7, 3)).isEqualTo(expected); + @Test + @DisplayName("Trivial 1-digit cages -> 6") + public void trivial1DigitCages6() { + + assertThat(helper.combinationsInCage( + 6, + 1)) + .isEqualTo(List.of(List.of(6))); + } + @Disabled("Remove to run test") @Test + @DisplayName("Trivial 1-digit cages -> 7") + public void trivial1DigitCages7() { + + assertThat(helper.combinationsInCage( + 7, + 1)) + .isEqualTo(List.of(List.of(7))); + + } + @Disabled("Remove to run test") + @Test + @DisplayName("Trivial 1-digit cages -> 8") + public void trivial1DigitCages8() { + + assertThat(helper.combinationsInCage( + 8, + 1)) + .isEqualTo(List.of(List.of(8))); + + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Trivial 1-digit cages -> 9") + public void trivial1DigitCages9() { + + assertThat(helper.combinationsInCage( + 9, + 1)) + .isEqualTo(List.of(List.of(9))); + + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Cage with sum 45 contains all digits 1:9") + public void cageWithSum45ContainsAllDigits19() { + + assertThat(helper.combinationsInCage( + 45, + 9)) + .isEqualTo(List.of(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9))); + + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Cage with only 1 possible combination") + public void cageWithOnly1PossibleCombination() { + + assertThat(helper.combinationsInCage( + 7, + 3)) + .isEqualTo(List.of(List.of(1, 2, 4))); + + } + + @Disabled("Remove to run test") + @Test @DisplayName("Cage with several combinations") - public void testCageWithSeveralCombinations() { - List> expected = List.of( + public void cageWithSeveralCombinations() { + + assertThat(helper.combinationsInCage( + 10, + 2)) + .isEqualTo(List.of( List.of(1, 9), List.of(2, 8), List.of(3, 7), List.of(4, 6) - ); - assertThat(helper.combinationsInCage(10, 2)).isEqualTo(expected); + )); + } - @Test @Disabled("Remove to run test") + @Test @DisplayName("Cage with several combinations that is restricted") - public void testCageWithSeveralCombinationsThatIsRestricted() { - List> expected = List.of( - List.of(2, 8), - List.of(3, 7) - ); - assertThat(helper.combinationsInCage(10, 2, List.of(1, 4))).isEqualTo(expected); + public void cageWithSeveralCombinationsThatIsRestricted() { + + assertThat(helper.combinationsInCage( + 10, + 2, + List.of(1, 4))) + .isEqualTo(List.of(List.of(2, 8), List.of(3, 7))); + } -} +} diff --git a/exercises/practice/kindergarten-garden/src/test/java/KindergartenGardenTest.java b/exercises/practice/kindergarten-garden/src/test/java/KindergartenGardenTest.java index e2b511869..0ff630a4d 100644 --- a/exercises/practice/kindergarten-garden/src/test/java/KindergartenGardenTest.java +++ b/exercises/practice/kindergarten-garden/src/test/java/KindergartenGardenTest.java @@ -1,194 +1,227 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; + import static org.assertj.core.api.Assertions.assertThat; public class KindergartenGardenTest { @Test - @DisplayName("garden with single student") - public void singleStudent() { - String garden = "RC\nGG"; - String student = "Alice"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.RADISHES, Plant.CLOVER, Plant.GRASS, Plant.GRASS); + @DisplayName("partial garden -> garden with single student") + public void partialGardenGardenWithSingleStudent() { + assertThat(new KindergartenGarden("RC\nGG") + .getPlantsOfStudent("Alice")) + .containsExactly( + Plant.RADISHES, + Plant.CLOVER, + Plant.GRASS, + Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("different garden with single student") - public void singleStudent2() { - String garden = "VC\nRC"; - String student = "Alice"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.VIOLETS, Plant.CLOVER, Plant.RADISHES, Plant.CLOVER); + @DisplayName("partial garden -> different garden with single student") + public void partialGardenDifferentGardenWithSingleStudent() { + assertThat(new KindergartenGarden("VC\nRC") + .getPlantsOfStudent("Alice")) + .containsExactly( + Plant.VIOLETS, + Plant.CLOVER, + Plant.RADISHES, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("garden with two students") - public void twoStudents() { - String garden = "VVCG\nVVRC"; - String student = "Bob"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.CLOVER, Plant.GRASS, Plant.RADISHES, Plant.CLOVER); + @DisplayName("partial garden -> garden with two students") + public void partialGardenGardenWithTwoStudents() { + assertThat(new KindergartenGarden("VVCG\nVVRC") + .getPlantsOfStudent("Bob")) + .containsExactly( + Plant.CLOVER, + Plant.GRASS, + Plant.RADISHES, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("second student's garden") - public void oneGardenSecondStudent() { - String garden = "VVCCGG\nVVCCGG"; - String student = "Bob"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.CLOVER, Plant.CLOVER, Plant.CLOVER, Plant.CLOVER); + @DisplayName("partial garden -> multiple students for the same garden with three " + + "students -> second student's garden") + public void partialGardenMultipleStudentsForTheSameGardenWithThreeStudentsSec() { + assertThat(new KindergartenGarden("VVCCGG\nVVCCGG") + .getPlantsOfStudent("Bob")) + .containsExactly( + Plant.CLOVER, + Plant.CLOVER, + Plant.CLOVER, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("third student's garden") - public void oneGardenThirdStudent() { - String garden = "VVCCGG\nVVCCGG"; - String student = "Charlie"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) + @DisplayName("partial garden -> multiple students for the same garden with three " + + "students -> third student's garden") + public void partialGardenMultipleStudentsForTheSameGardenWithThreeStudentsThi() { + assertThat(new KindergartenGarden("VVCCGG\nVVCCGG") + .getPlantsOfStudent("Charlie")) .containsExactly(Plant.GRASS, Plant.GRASS, Plant.GRASS, Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("for Alice, first student's garden") - public void fullGardenForAlice() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Alice"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.VIOLETS, Plant.RADISHES, Plant.VIOLETS, Plant.RADISHES); + @DisplayName("full garden -> for Alice, first student's garden") + public void fullGardenForAliceFirstStudentSGarden() { + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Alice")) + .containsExactly( + Plant.VIOLETS, + Plant.RADISHES, + Plant.VIOLETS, + Plant.RADISHES); } @Disabled("Remove to run test") @Test - @DisplayName("for Bob, second student's garden") - public void fullGardenForBob() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Bob"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.CLOVER, Plant.GRASS, Plant.CLOVER, Plant.CLOVER); + @DisplayName("full garden -> for Bob, second student's garden") + public void fullGardenForBobSecondStudentSGarden() { + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Bob")) + .containsExactly( + Plant.CLOVER, + Plant.GRASS, + Plant.CLOVER, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("for Charlie") + @DisplayName("full garden -> for Charlie") public void fullGardenForCharlie() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Charlie"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.VIOLETS, Plant.VIOLETS, Plant.CLOVER, Plant.GRASS); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Charlie")) + .containsExactly( + Plant.VIOLETS, + Plant.VIOLETS, + Plant.CLOVER, + Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("for David") + @DisplayName("full garden -> for David") public void fullGardenForDavid() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "David"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.RADISHES, Plant.VIOLETS, Plant.CLOVER, Plant.RADISHES); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("David")) + .containsExactly( + Plant.RADISHES, + Plant.VIOLETS, + Plant.CLOVER, + Plant.RADISHES); } @Disabled("Remove to run test") @Test - @DisplayName("for Eve") + @DisplayName("full garden -> for Eve") public void fullGardenForEve() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Eve"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.CLOVER, Plant.GRASS, Plant.RADISHES, Plant.GRASS); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Eve")) + .containsExactly( + Plant.CLOVER, + Plant.GRASS, + Plant.RADISHES, + Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("for Fred") + @DisplayName("full garden -> for Fred") public void fullGardenForFred() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Fred"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.GRASS, Plant.CLOVER, Plant.VIOLETS, Plant.CLOVER); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Fred")) + .containsExactly( + Plant.GRASS, + Plant.CLOVER, + Plant.VIOLETS, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("for Ginny") + @DisplayName("full garden -> for Ginny") public void fullGardenForGinny() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Ginny"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.CLOVER, Plant.GRASS, Plant.GRASS, Plant.CLOVER); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Ginny")) + .containsExactly( + Plant.CLOVER, + Plant.GRASS, + Plant.GRASS, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("for Harriet") + @DisplayName("full garden -> for Harriet") public void fullGardenForHarriet() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Harriet"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.VIOLETS, Plant.RADISHES, Plant.RADISHES, Plant.VIOLETS); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Harriet")) + .containsExactly( + Plant.VIOLETS, + Plant.RADISHES, + Plant.RADISHES, + Plant.VIOLETS); } @Disabled("Remove to run test") @Test - @DisplayName("for Ileana") + @DisplayName("full garden -> for Ileana") public void fullGardenForIleana() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Ileana"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.GRASS, Plant.CLOVER, Plant.VIOLETS, Plant.CLOVER); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Ileana")) + .containsExactly( + Plant.GRASS, + Plant.CLOVER, + Plant.VIOLETS, + Plant.CLOVER); } @Disabled("Remove to run test") @Test - @DisplayName("for Joseph") + @DisplayName("full garden -> for Joseph") public void fullGardenForJoseph() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Joseph"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.VIOLETS, Plant.CLOVER, Plant.VIOLETS, Plant.GRASS); + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Joseph")) + .containsExactly( + Plant.VIOLETS, + Plant.CLOVER, + Plant.VIOLETS, + Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("for Kincaid, second to last student's garden") - public void fullGardenForKincaid() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Kincaid"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.GRASS, Plant.CLOVER, Plant.CLOVER, Plant.GRASS); + @DisplayName("full garden -> for Kincaid, second to last student's garden") + public void fullGardenForKincaidSecondToLastStudentSGarden() { + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Kincaid")) + .containsExactly( + Plant.GRASS, + Plant.CLOVER, + Plant.CLOVER, + Plant.GRASS); } @Disabled("Remove to run test") @Test - @DisplayName("for Larry, last student's garden") - public void fullGardenForLarry() { - String garden = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV"; - String student = "Larry"; - - assertThat(new KindergartenGarden(garden).getPlantsOfStudent(student)) - .containsExactly(Plant.GRASS, Plant.VIOLETS, Plant.CLOVER, Plant.VIOLETS); + @DisplayName("full garden -> for Larry, last student's garden") + public void fullGardenForLarryLastStudentSGarden() { + assertThat(new KindergartenGarden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") + .getPlantsOfStudent("Larry")) + .containsExactly( + Plant.GRASS, + Plant.VIOLETS, + Plant.CLOVER, + Plant.VIOLETS); } } diff --git a/exercises/practice/knapsack/src/test/java/KnapsackTest.java b/exercises/practice/knapsack/src/test/java/KnapsackTest.java index 166c12cbe..70c81f3e9 100644 --- a/exercises/practice/knapsack/src/test/java/KnapsackTest.java +++ b/exercises/practice/knapsack/src/test/java/KnapsackTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,119 +6,119 @@ import static org.assertj.core.api.Assertions.assertThat; - public class KnapsackTest { - private Knapsack knapsack; - - @BeforeEach - public void setup() { - knapsack = new Knapsack(); - } + private Knapsack knapsack = new Knapsack(); @Test @DisplayName("no items") - public void testNoItems() { + public void noItems() { List items = List.of(); - assertThat(knapsack.maximumValue(100, items)).isEqualTo(0); + + assertThat(knapsack.maximumValue(100, items)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("one item, too heavy") - public void testOneItemTooHeavy() { - List items = List.of( - new Item(100, 1) - ); + public void oneItemTooHeavy() { + List items = List.of(new Item(100, 1)); - assertThat(knapsack.maximumValue(10, items)).isEqualTo(0); + assertThat(knapsack.maximumValue(10, items)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("five items (cannot be greedy by weight)") - public void testFiveItemsCannotBeGreedyByWeight() { + public void fiveItemsCannotBeGreedyByWeight() { List items = List.of( - new Item(2, 5), - new Item(2, 5), - new Item(2, 5), - new Item(2, 5), - new Item(10, 21) + new Item(2, 5), + new Item(2, 5), + new Item(2, 5), + new Item(2, 5), + new Item(10, 21) ); - assertThat(knapsack.maximumValue(10, items)).isEqualTo(21); + assertThat(knapsack.maximumValue(10, items)) + .isEqualTo(21); } @Disabled("Remove to run test") @Test @DisplayName("five items (cannot be greedy by value)") - public void testFiveItemsCannotBeGreedyByValue() { + public void fiveItemsCannotBeGreedyByValue() { List items = List.of( - new Item(2, 20), - new Item(2, 20), - new Item(2, 20), - new Item(2, 20), - new Item(10, 50) + new Item(2, 20), + new Item(2, 20), + new Item(2, 20), + new Item(2, 20), + new Item(10, 50) ); - assertThat(knapsack.maximumValue(10, items)).isEqualTo(80); + assertThat(knapsack.maximumValue(10, items)) + .isEqualTo(80); } @Disabled("Remove to run test") @Test @DisplayName("example knapsack") - public void testExampleKnapsack() { + public void exampleKnapsack() { List items = List.of( - new Item(5, 10), - new Item(4, 40), - new Item(6, 30), - new Item(4, 50) + new Item(5, 10), + new Item(4, 40), + new Item(6, 30), + new Item(4, 50) ); - assertThat(knapsack.maximumValue(10, items)).isEqualTo(90); + assertThat(knapsack.maximumValue(10, items)) + .isEqualTo(90); } @Disabled("Remove to run test") @Test @DisplayName("8 items") - public void testEightItems() { + public void test8Items() { List items = List.of( - new Item(25, 350), - new Item(35, 400), - new Item(45, 450), - new Item(5, 20), - new Item(25, 70), - new Item(3, 8), - new Item(2, 5), - new Item(2, 5) + new Item(25, 350), + new Item(35, 400), + new Item(45, 450), + new Item(5, 20), + new Item(25, 70), + new Item(3, 8), + new Item(2, 5), + new Item(2, 5) ); - assertThat(knapsack.maximumValue(104, items)).isEqualTo(900); + assertThat(knapsack.maximumValue(104, items)) + .isEqualTo(900); } @Disabled("Remove to run test") @Test @DisplayName("15 items") - public void testFifteenItems() { + public void test15Items() { List items = List.of( - new Item(70, 135), - new Item(73, 139), - new Item(77, 149), - new Item(80, 150), - new Item(82, 156), - new Item(87, 163), - new Item(90, 173), - new Item(94, 184), - new Item(98, 192), - new Item(106, 201), - new Item(110, 210), - new Item(113, 214), - new Item(115, 221), - new Item(118, 229), - new Item(120, 240) + new Item(70, 135), + new Item(73, 139), + new Item(77, 149), + new Item(80, 150), + new Item(82, 156), + new Item(87, 163), + new Item(90, 173), + new Item(94, 184), + new Item(98, 192), + new Item(106, 201), + new Item(110, 210), + new Item(113, 214), + new Item(115, 221), + new Item(118, 229), + new Item(120, 240) ); - assertThat(knapsack.maximumValue(750, items)).isEqualTo(1458); + assertThat(knapsack.maximumValue(750, items)) + .isEqualTo(1458); } } diff --git a/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java b/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java index 554eaa0fe..86618a193 100644 --- a/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java +++ b/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java @@ -9,142 +9,112 @@ public class LargestSeriesProductCalculatorTest { @Test @DisplayName("finds the largest product if span equals length") - public void testCorrectlyCalculatesLargestProductWhenSeriesLengthEqualsStringToSearchLength() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("29"); - long expectedProduct = 18; + public void findsTheLargestProductIfSpanEqualsLength() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(2); + assertThat(new LargestSeriesProductCalculator("29") + .calculateLargestProductForSeriesLength(2)) + .isEqualTo(18L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 2 with numbers in order") - public void testCorrectlyCalculatesLargestProductOfLengthTwoWithNumbersInOrder() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("0123456789"); - long expectedProduct = 72; + public void canFindTheLargestProductOf2WithNumbersInOrder() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(2); + assertThat(new LargestSeriesProductCalculator("0123456789") + .calculateLargestProductForSeriesLength(2)) + .isEqualTo(72L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 2") - public void testCorrectlyCalculatesLargestProductOfLengthTwoWithNumbersNotInOrder() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("576802143"); - long expectedProduct = 48; + public void canFindTheLargestProductOf2() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(2); + assertThat(new LargestSeriesProductCalculator("576802143") + .calculateLargestProductForSeriesLength(2)) + .isEqualTo(48L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 3 with numbers in order") - public void testCorrectlyCalculatesLargestProductOfLengthThreeWithNumbersInOrder() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("0123456789"); - long expectedProduct = 504; + public void canFindTheLargestProductOf3WithNumbersInOrder() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(3); + assertThat(new LargestSeriesProductCalculator("0123456789") + .calculateLargestProductForSeriesLength(3)) + .isEqualTo(504L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 3") - public void testCorrectlyCalculatesLargestProductOfLengthThreeWithNumbersNotInOrder() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("1027839564"); - long expectedProduct = 270; + public void canFindTheLargestProductOf3() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(3); + assertThat(new LargestSeriesProductCalculator("1027839564") + .calculateLargestProductForSeriesLength(3)) + .isEqualTo(270L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 5 with numbers in order") - public void testCorrectlyCalculatesLargestProductOfLengthFiveWithNumbersInOrder() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("0123456789"); - long expectedProduct = 15120; + public void canFindTheLargestProductOf5WithNumbersInOrder() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(5); + assertThat(new LargestSeriesProductCalculator("0123456789") + .calculateLargestProductForSeriesLength(5)) + .isEqualTo(15120L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("can get the largest product of a big number") - public void testCorrectlyCalculatesLargestProductInLongStringToSearchV1() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator( - "73167176531330624919225119674426574742355349194934"); + public void canGetTheLargestProductOfABigNumber() { - long expectedProduct = 23520; + assertThat(new LargestSeriesProductCalculator("73167176531330624919225119674426574742355349194934") + .calculateLargestProductForSeriesLength(6)) + .isEqualTo(23520L); - long actualProduct = calculator.calculateLargestProductForSeriesLength(6); - - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("reports zero if the only digits are zero") - public void testCorrectlyCalculatesLargestProductOfZeroIfAllDigitsAreZeroes() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("0000"); - long expectedProduct = 0; + public void reportsZeroIfTheOnlyDigitsAreZero() { - long actualProduct = calculator.calculateLargestProductForSeriesLength(2); + assertThat(new LargestSeriesProductCalculator("0000") + .calculateLargestProductForSeriesLength(2)) + .isEqualTo(0L); - assertThat(actualProduct).isEqualTo(expectedProduct); } @Disabled("Remove to run test") @Test @DisplayName("reports zero if all spans include zero") - public void testCorrectlyCalculatesLargestProductOfZeroIfAllSeriesOfGivenLengthContainZero() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("99099"); - long expectedProduct = 0; - - long actualProduct = calculator.calculateLargestProductForSeriesLength(3); + public void reportsZeroIfAllSpansIncludeZero() { - assertThat(actualProduct).isEqualTo(expectedProduct); - } + assertThat(new LargestSeriesProductCalculator("99099") + .calculateLargestProductForSeriesLength(3)) + .isEqualTo(0L); - @Disabled("Remove to run test") - @Test - @DisplayName("rejects span longer than string length") - public void testSeriesLengthLongerThanLengthOfStringToTestIsRejected() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("123"); - - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> calculator.calculateLargestProductForSeriesLength(4)) - .withMessage("Series length must be less than or equal to the length of the string to search."); } @Disabled("Remove to run test") @Test @DisplayName("rejects invalid character in digits") - public void testStringToSearchContainingNonDigitCharacterIsRejected() { + public void rejectsInvalidCharacterInDigits() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new LargestSeriesProductCalculator("1234a5")) + .isThrownBy(() -> new LargestSeriesProductCalculator("1234a5") + .calculateLargestProductForSeriesLength(2)) .withMessage("String to search may only contain digits."); - } - @Disabled("Remove to run test") - @Test - @DisplayName("integer overflow") - public void testForIntegerOverflow() { - LargestSeriesProductCalculator calculator = new LargestSeriesProductCalculator("9999999999"); - long expectedProduct = 3486784401L; - - long actualProduct = calculator.calculateLargestProductForSeriesLength(10); - - assertThat(actualProduct).isEqualTo(expectedProduct); } + } diff --git a/exercises/practice/leap/src/test/java/LeapTest.java b/exercises/practice/leap/src/test/java/LeapTest.java index b61e8c2d9..9de32dc53 100644 --- a/exercises/practice/leap/src/test/java/LeapTest.java +++ b/exercises/practice/leap/src/test/java/LeapTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,73 +6,75 @@ public class LeapTest { - private Leap leap; - - @BeforeEach - public void setup() { - leap = new Leap(); - } - @Test @DisplayName("year not divisible by 4 in common year") - public void testYearNotDivBy4InCommonYear() { - assertThat(leap.isLeapYear(2015)).isFalse(); + public void yearNotDivisibleBy4InCommonYear() { + assertThat(new Leap().isLeapYear(2015)) + .isEqualTo(false); } @Disabled("Remove to run test") @Test - @DisplayName("year divisible by 2, not divisible by 4 in common year\"") - public void testYearDivBy2NotDivBy4InCommonYear() { - assertThat(leap.isLeapYear(1970)).isFalse(); + @DisplayName("year divisible by 2, not divisible by 4 in common year") + public void yearDivisibleBy2NotDivisibleBy4InCommonYear() { + assertThat(new Leap().isLeapYear(1970)) + .isEqualTo(false); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 4, not divisible by 100 in leap year") - public void testYearDivBy4NotDivBy100InLeapYear() { - assertThat(leap.isLeapYear(1996)).isTrue(); + public void yearDivisibleBy4NotDivisibleBy100InLeapYear() { + assertThat(new Leap().isLeapYear(1996)) + .isEqualTo(true); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 4 and 5 is still a leap year") - public void testYearDivBy4And5InLeapYear() { - assertThat(leap.isLeapYear(1960)).isTrue(); + public void yearDivisibleBy4And5IsStillALeapYear() { + assertThat(new Leap().isLeapYear(1960)) + .isEqualTo(true); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 100, not divisible by 400 in common year") - public void testYearDivBy100NotDivBy400InCommonYear() { - assertThat(leap.isLeapYear(2100)).isFalse(); + public void yearDivisibleBy100NotDivisibleBy400InCommonYear() { + assertThat(new Leap().isLeapYear(2100)) + .isEqualTo(false); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 100 but not by 3 is still not a leap year") - public void testYearDivBy100NotDivBy3IsNotLeapYear() { - assertThat(leap.isLeapYear(1900)).isFalse(); + public void yearDivisibleBy100ButNotBy3IsStillNotALeapYear() { + assertThat(new Leap().isLeapYear(1900)) + .isEqualTo(false); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 400 is leap year") - public void testYearDivBy400InLeapYear() { - assertThat(leap.isLeapYear(2000)).isTrue(); + public void yearDivisibleBy400IsLeapYear() { + assertThat(new Leap().isLeapYear(2000)) + .isEqualTo(true); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 400 but not by 125 is still a leap year") - public void testYearDivBy400NotDivBy125IsLeapYear() { - assertThat(leap.isLeapYear(2400)).isTrue(); + public void yearDivisibleBy400ButNotBy125IsStillALeapYear() { + assertThat(new Leap().isLeapYear(2400)) + .isEqualTo(true); } @Disabled("Remove to run test") @Test @DisplayName("year divisible by 200, not divisible by 400 in common year") - public void testYearDivBy200NotDivBy400InCommonYear() { - assertThat(leap.isLeapYear(1800)).isFalse(); + public void yearDivisibleBy200NotDivisibleBy400InCommonYear() { + assertThat(new Leap().isLeapYear(1800)) + .isEqualTo(false); } } diff --git a/exercises/practice/ledger/src/test/java/LedgerTest.java b/exercises/practice/ledger/src/test/java/LedgerTest.java index 15c022ee4..2f43f31d7 100644 --- a/exercises/practice/ledger/src/test/java/LedgerTest.java +++ b/exercises/practice/ledger/src/test/java/LedgerTest.java @@ -1,203 +1,171 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(LocaleExtension.class) public class LedgerTest { - private static final String US_LOCALE = "en-US"; - private static final String NL_LOCALE = "nl-NL"; - - private static final String USD_CURRENCY = "USD"; - private static final String EUR_CURRENCY = "EUR"; - - private Ledger ledger; + private Ledger ledger = new Ledger(); - @BeforeEach - public void setUp() throws Exception { - ledger = new Ledger(); - } - - @Disabled("Remove to run test") @Test @DisplayName("empty ledger") - public void emptyLedgerUS() { - var entries = new Ledger.LedgerEntry[] {}; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - String expected = "Date | Description | Change "; - assertThat(actual).isEqualTo(expected); + public void emptyLedger() { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{})) + .isEqualTo("Date | Description | Change "); } - + @Disabled("Remove to run test") @Test @DisplayName("one entry") public void oneEntry() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-01-01", "Buy present", -1000) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - String expected = "Date | Description | Change \n" - + "01/01/2015 | Buy present | ($10.00)"; - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Date | Description | Change \n" + + "01/01/2015 | Buy present | ($10.00)"); } - + @Disabled("Remove to run test") @Test @DisplayName("credit and debit") public void creditAndDebit() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-01-02", "Get present", 1000), ledger.createLedgerEntry("2015-01-01", "Buy present", -1000) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - String expected = "Date | Description | Change \n" + })) + .isEqualTo("Date | Description | Change \n" + "01/01/2015 | Buy present | ($10.00)\n" - + "01/02/2015 | Get present | $10.00 "; - - assertThat(actual).isEqualTo(expected); + + "01/02/2015 | Get present | $10.00 "); } - - @Disabled("Remove to run test") - @Test - @DisplayName("multiple entries on same date ordered by description") - public void multipleEntriesOnSameDateOrderedByDescription() { - var entries = new Ledger.LedgerEntry[] { - ledger.createLedgerEntry("2015-01-01", "Get present", 1000), - ledger.createLedgerEntry("2015-01-01", "Buy present", -1000) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - String expected = "Date | Description | Change \n" - + "01/01/2015 | Buy present | ($10.00)\n" - + "01/01/2015 | Get present | $10.00 "; - - assertThat(actual).isEqualTo(expected); - } - @Disabled("Remove to run test") @Test @DisplayName("final order tie breaker is change") public void finalOrderTieBreakerIsChange() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-01-01", "Something", 0), ledger.createLedgerEntry("2015-01-01", "Something", -1), ledger.createLedgerEntry("2015-01-01", "Something", 1) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - String expected = "Date | Description | Change \n" + })) + .isEqualTo("Date | Description | Change \n" + "01/01/2015 | Something | ($0.01)\n" + "01/01/2015 | Something | $0.00 \n" - + "01/01/2015 | Something | $0.01 "; - - assertThat(actual).isEqualTo(expected); + + "01/01/2015 | Something | $0.01 "); } - + @Disabled("Remove to run test") @Test @DisplayName("overlong description is truncated") - public void overlongDescriptions() { - var entries = new Ledger.LedgerEntry[] { + public void overlongDescriptionIsTruncated() { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-01-01", "Freude schoner Gotterfunken", -123456) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - String expected = "Date | Description | Change \n" - + "01/01/2015 | Freude schoner Gotterf... | ($1,234.56)"; - - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Date | Description | Change \n" + + "01/01/2015 | Freude schoner Gotterf... | ($1,234.56)"); } - + @Disabled("Remove to run test") @Test @DisplayName("euros") public void euros() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "EUR", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-01-01", "Buy present", -1000) - }; - - String actual = ledger.format(EUR_CURRENCY, US_LOCALE, entries); - - var expected = "Date | Description | Change \n" - + "01/01/2015 | Buy present | (€10.00)"; - - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Date | Description | Change \n" + + "01/01/2015 | Buy present | (€10.00)"); } - + @Disabled("Remove to run test") @Test @DisplayName("Dutch locale") public void dutchLocale() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "nl-NL", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-03-12", "Buy present", 123456) - }; - - String actual = ledger.format(USD_CURRENCY, NL_LOCALE, entries); - - var expected = "Datum | Omschrijving | Verandering \n" - + "12/03/2015 | Buy present | $ 1.234,56 "; - - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Datum | Omschrijving | Verandering \n" + + "12/03/2015 | Buy present | $ 1.234,56 "); } - + @Disabled("Remove to run test") @Test @DisplayName("Dutch locale and euros") public void dutchLocaleAndEuros() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "EUR", + "nl-NL", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-03-12", "Buy present", 123456) - }; - - String actual = ledger.format(EUR_CURRENCY, NL_LOCALE, entries); - - var expected = "Datum | Omschrijving | Verandering \n" - + "12/03/2015 | Buy present | € 1.234,56 "; - - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Datum | Omschrijving | Verandering \n" + + "12/03/2015 | Buy present | € 1.234,56 "); } - + @Disabled("Remove to run test") @Test @DisplayName("Dutch negative number with 3 digits before decimal point") public void dutchNegativeNumberWith3DigitsBeforeDecimalPoint() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "nl-NL", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-03-12", "Buy present", -12345) - }; - - String actual = ledger.format(USD_CURRENCY, NL_LOCALE, entries); - - var expected = "Datum | Omschrijving | Verandering \n" - + "12/03/2015 | Buy present | $ -123,45 "; - - assertThat(actual).isEqualTo(expected); + })) + .isEqualTo("Datum | Omschrijving | Verandering \n" + + "12/03/2015 | Buy present | $ -123,45 "); } - + @Disabled("Remove to run test") @Test @DisplayName("American negative number with 3 digits before decimal point") public void americanNegativeNumberWith3DigitsBeforeDecimalPoint() { - var entries = new Ledger.LedgerEntry[] { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ ledger.createLedgerEntry("2015-03-12", "Buy present", -12345) - }; - - String actual = ledger.format(USD_CURRENCY, US_LOCALE, entries); - - var expected = "Date | Description | Change \n" - + "03/12/2015 | Buy present | ($123.45)"; + })) + .isEqualTo("Date | Description | Change \n" + + "03/12/2015 | Buy present | ($123.45)"); + } - assertThat(actual).isEqualTo(expected); + @Disabled("Remove to run test") + @Test + @DisplayName("multiple entries on same date ordered by description") + public void multipleEntriesOnSameDateOrderedByDescription() { + assertThat(ledger.format( + "USD", + "en-US", + new Ledger.LedgerEntry[]{ + ledger.createLedgerEntry("2015-01-01", "Get present", 1000), + ledger.createLedgerEntry("2015-01-01", "Buy present", -1000) + })) + .isEqualTo("Date | Description | Change \n" + + "01/01/2015 | Buy present | ($10.00)\n" + + "01/01/2015 | Get present | $10.00 "); } + } diff --git a/exercises/practice/linked-list/src/test/java/DoublyLinkedListTest.java b/exercises/practice/linked-list/src/test/java/DoublyLinkedListTest.java index 365d92088..05c6d5f03 100644 --- a/exercises/practice/linked-list/src/test/java/DoublyLinkedListTest.java +++ b/exercises/practice/linked-list/src/test/java/DoublyLinkedListTest.java @@ -10,21 +10,17 @@ public class DoublyLinkedListTest { @DisplayName("pop gets element from the list") public void popGetsElementFromTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(7); - assertThat(list.pop()).isEqualTo(7); } @Disabled("Remove to run test") @Test @DisplayName("push/pop respectively add/remove at the end of the list") - public void pushAndPopRespectivelyAddsAndRemovesAtEndOfList() { + public void pushPopRespectivelyAddRemoveAtTheEndOfTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(11); list.push(13); - assertThat(list.pop()).isEqualTo(13); assertThat(list.pop()).isEqualTo(11); } @@ -34,9 +30,7 @@ public void pushAndPopRespectivelyAddsAndRemovesAtEndOfList() { @DisplayName("shift gets an element from the list") public void shiftGetsAnElementFromTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(17); - assertThat(list.shift()).isEqualTo(17); } @@ -45,10 +39,8 @@ public void shiftGetsAnElementFromTheList() { @DisplayName("shift gets first element from the list") public void shiftGetsFirstElementFromTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(23); list.push(5); - assertThat(list.shift()).isEqualTo(23); assertThat(list.shift()).isEqualTo(5); } @@ -58,64 +50,53 @@ public void shiftGetsFirstElementFromTheList() { @DisplayName("unshift adds element at start of the list") public void unshiftAddsElementAtStartOfTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.unshift(23); list.unshift(5); - assertThat(list.shift()).isEqualTo(5); assertThat(list.shift()).isEqualTo(23); } @Disabled("Remove to run test") @Test - @DisplayName("pop push shift unshift can be used in any order") - public void popPushShiftUnshiftCanBeUsedInAnyOrder() { - DoublyLinkedList list = new DoublyLinkedList<>(); - - list.push("one"); - list.push("two"); - - assertThat(list.pop()).isEqualTo("two"); - - list.push("three"); - - assertThat(list.shift()).isEqualTo("one"); - - list.unshift("four"); - list.push("five"); - - assertThat(list.shift()).isEqualTo("four"); - assertThat(list.pop()).isEqualTo("five"); - assertThat(list.shift()).isEqualTo("three"); + @DisplayName("pop, push, shift, and unshift can be used in any order") + public void popPushShiftAndUnshiftCanBeUsedInAnyOrder() { + DoublyLinkedList list = new DoublyLinkedList<>(); + list.push(1); + list.push(2); + assertThat(list.pop()).isEqualTo(2); + list.push(3); + assertThat(list.shift()).isEqualTo(1); + list.unshift(4); + list.push(5); + assertThat(list.shift()).isEqualTo(4); + assertThat(list.pop()).isEqualTo(5); + assertThat(list.shift()).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("popping to empty doesn't break the list") - public void poppingToEmptyDoesNotBreakTheList() { + public void poppingToEmptyDoesnTBreakTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(41); list.push(59); list.pop(); list.pop(); list.push(47); - assertThat(list.pop()).isEqualTo(47); } @Disabled("Remove to run test") @Test @DisplayName("shifting to empty doesn't break the list") - public void shiftingToEmptyDoesNotBreakTheList() { + public void shiftingToEmptyDoesnTBreakTheList() { DoublyLinkedList list = new DoublyLinkedList<>(); - list.push(41); list.push(59); list.shift(); list.shift(); list.push(47); - assertThat(list.shift()).isEqualTo(47); } + } diff --git a/exercises/practice/list-ops/src/test/java/ListOpsTest.java b/exercises/practice/list-ops/src/test/java/ListOpsTest.java index d604626b6..94691dedc 100644 --- a/exercises/practice/list-ops/src/test/java/ListOpsTest.java +++ b/exercises/practice/list-ops/src/test/java/ListOpsTest.java @@ -9,60 +9,59 @@ public class ListOpsTest { @Test - @DisplayName("empty lists") - public void testAppendingEmptyLists() { + @DisplayName("append entries to a list and return the new list -> empty lists") + public void appendEntriesToAListAndReturnTheNewListEmptyLists() { assertThat(ListOps.append(List.of(), List.of())).isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("list to empty list") - public void testAppendingListToEmptyList() { - assertThat(ListOps.append(List.of(), List.of('1', '2', '3', '4'))) - .containsExactly('1', '2', '3', '4'); + @DisplayName("append entries to a list and return the new list -> list to empty list") + public void appendEntriesToAListAndReturnTheNewListListToEmptyList() { + assertThat(ListOps.append(List.of(), List.of(1, 2, 3, 4))) + .isEqualTo(List.of(1, 2, 3, 4)); } @Disabled("Remove to run test") @Test - @DisplayName("empty list to list") - public void testAppendingEmptyListToList() { - assertThat(ListOps.append(List.of('1', '2', '3', '4'), List.of())) - .containsExactly('1', '2', '3', '4'); + @DisplayName("append entries to a list and return the new list -> empty list to list") + public void appendEntriesToAListAndReturnTheNewListEmptyListToList() { + assertThat(ListOps.append(List.of(1, 2, 3, 4), List.of())) + .isEqualTo(List.of(1, 2, 3, 4)); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty lists") - public void testAppendingNonEmptyLists() { - assertThat(ListOps.append(List.of("1", "2"), List.of("2", "3", "4", "5"))) - .containsExactly("1", "2", "2", "3", "4", "5"); + @DisplayName("append entries to a list and return the new list -> non-empty lists") + public void appendEntriesToAListAndReturnTheNewListNonEmptyLists() { + assertThat(ListOps.append(List.of(1, 2), List.of(2, 3, 4, 5))) + .isEqualTo(List.of(1, 2, 2, 3, 4, 5)); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testConcatEmptyList() { + @DisplayName("concatenate a list of lists -> empty list") + public void concatenateAListOfListsEmptyList() { assertThat(ListOps.concat(List.of())).isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("list of lists") - public void testConcatListOfLists() { + @DisplayName("concatenate a list of lists -> list of lists") + public void concatenateAListOfListsListOfLists() { List> listOfLists = List.of( List.of('1', '2'), List.of('3'), List.of(), List.of('4', '5', '6') ); - assertThat(ListOps.concat(listOfLists)).containsExactly('1', '2', '3', '4', '5', '6'); } @Disabled("Remove to run test") @Test - @DisplayName("list of nested lists") - public void testConcatListOfNestedLists() { + @DisplayName("concatenate a list of lists -> list of nested lists") + public void concatenateAListOfListsListOfNestedLists() { List>> listOfNestedLists = List.of( List.of( List.of('1'), @@ -78,173 +77,146 @@ public void testConcatListOfNestedLists() { List.of('4', '5', '6') ) ); - assertThat(ListOps.concat(listOfNestedLists)) - .containsExactly( + .isEqualTo(List.of( List.of('1'), List.of('2'), List.of('3'), List.of(), - List.of('4', '5', '6')); + List.of('4', '5', '6') + )); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testFilteringEmptyList() { + @DisplayName("filter list returning only values that satisfy the filter function -> empty list") + public void filterListReturningOnlyValuesThatSatisfyTheFilterFunctionEmptyLis() { assertThat(ListOps.filter(List.of(), integer -> integer % 2 == 1)) .isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty list") - public void testFilteringNonEmptyList() { + @DisplayName("filter list returning only values that satisfy the filter function -> non-empty list") + public void filterListReturningOnlyValuesThatSatisfyTheFilterFunctionNonEmpty() { assertThat(ListOps.filter(List.of(1, 2, 3, 5), integer -> integer % 2 == 1)) .containsExactly(1, 3, 5); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testSizeOfEmptyList() { + @DisplayName("returns the length of a list -> empty list") + public void returnsTheLengthOfAListEmptyList() { assertThat(ListOps.size(List.of())).isEqualTo(0); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty list") - public void testSizeOfNonEmptyList() { + @DisplayName("returns the length of a list -> non-empty list") + public void returnsTheLengthOfAListNonEmptyList() { assertThat(ListOps.size(List.of("one", "two", "three", "four"))).isEqualTo(4); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testTransformingEmptyList() { + @DisplayName("return a list of elements whose values equal the list value " + + "transformed by the mapping function -> empty list") + public void returnAListOfElementsWhoseValuesEqualTheListValueTransformedByThe() { assertThat(ListOps.map(List.of(), integer -> integer + 1)).isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty list") - public void testTransformingNonEmptyList() { + @DisplayName("return a list of elements whose values equal the list value " + + "transformed by the mapping function -> non-empty list") + public void returnAListOfElementsWhoseValuesEqualTheListValueTransformedByThe2() { assertThat(ListOps.map(List.of(1, 3, 5, 7), integer -> integer + 1)) .containsExactly(2, 4, 6, 8); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testFoldLeftEmptyList() { - assertThat( - ListOps.foldLeft( - List.of(), - 2.0, - (acc, el) -> el * acc)) + @DisplayName("folds (reduces) the given list from the left with a function -> empty list") + public void foldsReducesTheGivenListFromTheLeftWithAFunctionEmptyList() { + assertThat(ListOps.foldLeft(List.of(), 2.0, (acc, el) -> el * acc)) .isEqualTo(2.0); } @Disabled("Remove to run test") @Test - @DisplayName("direction independent function applied to non-empty list") - public void testFoldLeftDirectionIndependentFunctionAppliedToNonEmptyList() { - assertThat( - ListOps.foldLeft( - List.of(1, 2, 3, 4), - 5, - (acc, el) -> el + acc)) + @DisplayName("folds (reduces) the given list from the left with a function -> " + + "direction independent function applied to non-empty list") + public void foldsReducesTheGivenListFromTheLeftWithAFunctionDirectionIndepend() { + assertThat(ListOps.foldLeft(List.of(1, 2, 3, 4), 5, Integer::sum)) .isEqualTo(15); } @Disabled("Remove to run test") @Test - @DisplayName("direction dependent function applied to non-empty list") - public void testFoldLeftDirectionDependentFunctionAppliedToNonEmptyList() { - assertThat( - ListOps.foldLeft( - List.of(1.0, 2.0, 3.0, 4.0), - 24.0, - (acc, el) -> el / acc)) + @DisplayName("folds (reduces) the given list from the left with a function -> " + + "direction dependent function applied to non-empty list") + public void foldsReducesTheGivenListFromTheLeftWithAFunctionDirectionDependen() { + assertThat(ListOps.foldLeft(List.of(1.0, 2.0, 3.0, 4.0), 24.0, (acc, el) -> el / acc)) .isEqualTo(64.0); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testFoldRightEmptyList() { - assertThat( - ListOps.foldRight( - List.of(), - 2.0, - (el, acc) -> acc * el)) + @DisplayName("folds (reduces) the given list from the right with a function -> empty list") + public void foldsReducesTheGivenListFromTheRightWithAFunctionEmptyList() { + assertThat(ListOps.foldRight(List.of(), 2.0, (el, acc) -> el * acc)) .isEqualTo(2.0); } @Disabled("Remove to run test") @Test - @DisplayName("direction independent function applied to non-empty list") - public void testFoldRightDirectionIndependentFunctionAppliedToNonEmptyList() { - assertThat( - ListOps.foldRight( - List.of(1, 2, 3, 4), - 5, - (el, acc) -> acc + el)) + @DisplayName("folds (reduces) the given list from the right with a function -> " + + "direction independent function applied to non-empty list") + public void foldsReducesTheGivenListFromTheRightWithAFunctionDirectionIndepen() { + assertThat(ListOps.foldRight(List.of(1, 2, 3, 4), 5, Integer::sum)) .isEqualTo(15); } @Disabled("Remove to run test") @Test - @DisplayName("direction dependent function applied to non-empty list") - public void testFoldRightDirectionDependentFunctionAppliedToNonEmptyList() { - assertThat( - ListOps.foldRight( - List.of(1.0, 2.0, 3.0, 4.0), - 24.0, - (el, acc) -> el / acc)) + @DisplayName("folds (reduces) the given list from the right with a function -> " + + "direction dependent function applied to non-empty list") + public void foldsReducesTheGivenListFromTheRightWithAFunctionDirectionDepende() { + assertThat(ListOps.foldRight(List.of(1.0, 2.0, 3.0, 4.0), 24.0, (el, acc) -> el / acc)) .isEqualTo(9.0); } @Disabled("Remove to run test") @Test - @DisplayName("empty list") - public void testReversingEmptyList() { + @DisplayName("reverse the elements of the list -> empty list") + public void reverseTheElementsOfTheListEmptyList() { assertThat(ListOps.reverse(List.of())).isEmpty(); } @Disabled("Remove to run test") @Test - @DisplayName("non-empty even-length list") - public void testReversingNonEmptyEvenLengthList() { + @DisplayName("reverse the elements of the list -> non-empty list") + public void reverseTheElementsOfTheListNonEmptyList() { assertThat(ListOps.reverse(List.of('1', '3', '5', '7'))) .containsExactly('7', '5', '3', '1'); } - - @Disabled("Remove to run test") - @Test - @DisplayName("reverse the elements of the list -> non-empty odd-length list") - public void testReversingNonEmptyOddLengthList() { - assertThat(ListOps.reverse(List.of(1, 3, 5, 7, 9, 11, 13))) - .containsExactly(13, 11, 9, 7, 5, 3, 1); - } @Disabled("Remove to run test") @Test - @DisplayName("list of lists is not flattened") - public void testReversingListOfListIsNotFlattened() { + @DisplayName("reverse the elements of the list -> list of lists is not flattened") + public void reverseTheElementsOfTheListListOfListsIsNotFlattened() { List> listOfLists = List.of( List.of('1', '2'), List.of('3'), List.of(), List.of('4', '5', '6') ); - - assertThat(ListOps.reverse(listOfLists)) - .containsExactly( - List.of('4', '5', '6'), - List.of(), - List.of('3'), - List.of('1', '2')); + assertThat(ListOps.reverse(listOfLists)).containsExactly( + List.of('4', '5', '6'), + List.of(), + List.of('3'), + List.of('1', '2') + ); } } diff --git a/exercises/practice/luhn/src/test/java/LuhnValidatorTest.java b/exercises/practice/luhn/src/test/java/LuhnValidatorTest.java index bc0c6d7dc..d60aaa8e5 100644 --- a/exercises/practice/luhn/src/test/java/LuhnValidatorTest.java +++ b/exercises/practice/luhn/src/test/java/LuhnValidatorTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,175 +5,181 @@ import static org.assertj.core.api.Assertions.assertThat; public class LuhnValidatorTest { - private LuhnValidator luhnValidator; - - @BeforeEach - public void setUp() { - luhnValidator = new LuhnValidator(); - } @Test @DisplayName("single digit strings can not be valid") - public void testSingleDigitStringInvalid() { - assertThat(luhnValidator.isValid("1")).isFalse(); + public void singleDigitStringsCanNotBeValid() { + assertThat(new LuhnValidator().isValid("1")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("a single zero is invalid") - public void testSingleZeroIsInvalid() { - assertThat(luhnValidator.isValid("0")).isFalse(); + public void aSingleZeroIsInvalid() { + assertThat(new LuhnValidator().isValid("0")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("a simple valid SIN that remains valid if reversed") - public void testSimpleValidSINReversedRemainsValid() { - assertThat(luhnValidator.isValid("059")).isTrue(); + public void aSimpleValidSinThatRemainsValidIfReversed() { + assertThat(new LuhnValidator().isValid("059")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("a simple valid SIN that becomes invalid if reversed") - public void testSimpleValidSINReversedBecomesInvalid() { - assertThat(luhnValidator.isValid("59")).isTrue(); + public void aSimpleValidSinThatBecomesInvalidIfReversed() { + assertThat(new LuhnValidator().isValid("59")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("a valid Canadian SIN") - public void testValidCanadianSINValid() { - assertThat(luhnValidator.isValid("055 444 285")).isTrue(); + public void aValidCanadianSin() { + assertThat(new LuhnValidator().isValid("055 444 285")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("invalid Canadian SIN") - public void testInvalidCanadianSINInvalid() { - assertThat(luhnValidator.isValid("055 444 286")).isFalse(); + public void invalidCanadianSin() { + assertThat(new LuhnValidator().isValid("055 444 286")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid credit card") - public void testInvalidCreditCardInvalid() { - assertThat(luhnValidator.isValid("8273 1232 7352 0569")).isFalse(); + public void invalidCreditCard() { + assertThat(new LuhnValidator().isValid("8273 1232 7352 0569")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid long number with an even remainder") - public void testInvalidLongNumberWithAnEvenRemainder() { - assertThat(luhnValidator.isValid("1 2345 6789 1234 5678 9012")).isFalse(); + public void invalidLongNumberWithAnEvenRemainder() { + assertThat(new LuhnValidator().isValid("1 2345 6789 1234 5678 9012")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("invalid long number with a remainder divisible by 5") - public void testInvalidLongNumberWithARemainderDivisibleBy5() { - assertThat(luhnValidator.isValid("1 2345 6789 1234 5678 9013")).isFalse(); + public void invalidLongNumberWithARemainderDivisibleBy5() { + assertThat(new LuhnValidator().isValid("1 2345 6789 1234 5678 9013")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("valid number with an even number of digits") - public void testValidNumberWithAnEvenNumberOfDigits() { - assertThat(luhnValidator.isValid("095 245 88")).isTrue(); + public void validNumberWithAnEvenNumberOfDigits() { + assertThat(new LuhnValidator().isValid("095 245 88")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("valid number with an odd number of spaces") - public void testValidNumberWithAnOddNumberOfSpaces() { - assertThat(luhnValidator.isValid("234 567 891 234")).isTrue(); + public void validNumberWithAnOddNumberOfSpaces() { + assertThat(new LuhnValidator().isValid("234 567 891 234")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("valid strings with a non-digit added at the end become invalid") - public void testValidStringsWithANonDigitAtEndInvalid() { - assertThat(luhnValidator.isValid("059a")).isFalse(); + public void validStringsWithANonDigitAddedAtTheEndBecomeInvalid() { + assertThat(new LuhnValidator().isValid("059a")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("valid strings with punctuation included become invalid") - public void testStringContainingPunctuationInvalid() { - assertThat(luhnValidator.isValid("055-444-285")).isFalse(); + public void validStringsWithPunctuationIncludedBecomeInvalid() { + assertThat(new LuhnValidator().isValid("055-444-285")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("valid strings with symbols included become invalid") - public void testStringContainingSymbolsInvalid() { - assertThat(luhnValidator.isValid("055# 444$ 285")).isFalse(); + public void validStringsWithSymbolsIncludedBecomeInvalid() { + assertThat(new LuhnValidator().isValid("055# 444$ 285")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("single zero with space is invalid") - public void testSingleSpaceWithZeroInvalid() { - assertThat(luhnValidator.isValid(" 0")).isFalse(); + public void singleZeroWithSpaceIsInvalid() { + assertThat(new LuhnValidator().isValid(" 0")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("more than a single zero is valid") - public void testMoreThanSingleZeroValid() { - assertThat(luhnValidator.isValid("0000 0")).isTrue(); + public void moreThanASingleZeroIsValid() { + assertThat(new LuhnValidator().isValid("0000 0")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("input digit 9 is correctly converted to output digit 9") - public void testDigitNineConvertedToOutputNine() { - assertThat(luhnValidator.isValid("091")).isTrue(); + public void inputDigit9IsCorrectlyConvertedToOutputDigit9() { + assertThat(new LuhnValidator().isValid("091")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("very long input is valid") - public void testVeryLongInputIsValid() { - assertThat(luhnValidator.isValid("9999999999 9999999999 9999999999 9999999999")).isTrue(); + public void veryLongInputIsValid() { + assertThat(new LuhnValidator().isValid("9999999999 9999999999 9999999999 9999999999")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("valid luhn with an odd number of digits and non zero first digit") - public void testValidLuhnWithOddNumberOfDigitsAndNonZeroFirstDigit() { - assertThat(luhnValidator.isValid("109")).isTrue(); + public void validLuhnWithAnOddNumberOfDigitsAndNonZeroFirstDigit() { + assertThat(new LuhnValidator().isValid("109")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("using ascii value for non-doubled non-digit isn't allowed") - public void testUsingASCIIValueForNonDoubledNonDigitNotAllowed() { - assertThat(luhnValidator.isValid("055b 444 285")).isFalse(); + public void usingAsciiValueForNonDoubledNonDigitIsnTAllowed() { + assertThat(new LuhnValidator().isValid("055b 444 285")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("using ascii value for doubled non-digit isn't allowed") - public void testUsingASCIIValueForDoubledNonDigitNotAllowed() { - assertThat(luhnValidator.isValid(":9")).isFalse(); + public void usingAsciiValueForDoubledNonDigitIsnTAllowed() { + assertThat(new LuhnValidator().isValid(":9")) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("non-numeric, non-space char in the middle with a sum that's divisible by 10 isn't allowed") - public void testNonNumericNonSpaceCharInMiddleWithSumDivisibleBy10IsNotAllowed() { - assertThat(luhnValidator.isValid("59%59")).isFalse(); + @DisplayName("non-numeric, non-space char in the middle with a sum that's divisible " + + "by 10 isn't allowed") + public void nonNumericNonSpaceCharInTheMiddleWithASumThatSDivisibleBy10IsnTAl() { + assertThat(new LuhnValidator().isValid("59%59")) + .isFalse(); } - /* The following test diverges from the canonical test data. This is because the corresponding canonical test does - * not account for Java specific functions (such as Character.getNumericValue()), which can be part of incorrect yet - * passing implementations. For more detail, check out issue #972 here: - * (https://github.com/exercism/java/issues/972). - */ - @Disabled("Remove to run test") - @Test - @DisplayName("string containing symbols is invalid (Java track specific)") - public void testStringContainingSymbolsIsInvalidJavaTrackSpecific() { - assertThat(luhnValidator.isValid("85&")).isFalse(); - } } diff --git a/exercises/practice/markdown/src/test/java/MarkdownTest.java b/exercises/practice/markdown/src/test/java/MarkdownTest.java index ec0f31d94..0fcf346c8 100644 --- a/exercises/practice/markdown/src/test/java/MarkdownTest.java +++ b/exercises/practice/markdown/src/test/java/MarkdownTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,180 +6,142 @@ public class MarkdownTest { - private Markdown markdown; - - @BeforeEach - public void setup() { - markdown = new Markdown(); - } - @Test @DisplayName("parses normal text as a paragraph") - public void normalTextAsAParagraph() { - String input = "This will be a paragraph"; - String expected = "

This will be a paragraph

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void parsesNormalTextAsAParagraph() { + assertThat(new Markdown().parse("This will be a paragraph")) + .isEqualTo("

This will be a paragraph

"); } @Disabled("Remove to run test") @Test @DisplayName("parsing italics") - public void italics() { - String input = "_This will be italic_"; - String expected = "

This will be italic

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void parsingItalics() { + assertThat(new Markdown().parse("_This will be italic_")) + .isEqualTo("

This will be italic

"); } @Disabled("Remove to run test") @Test @DisplayName("parsing bold text") - public void boldText() { - String input = "__This will be bold__"; - String expected = "

This will be bold

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void parsingBoldText() { + assertThat(new Markdown().parse("__This will be bold__")) + .isEqualTo("

This will be bold

"); } @Disabled("Remove to run test") @Test @DisplayName("mixed normal, italics and bold text") - public void normalItalicsAndBoldText() { - String input = "This will _be_ __mixed__"; - String expected = "

This will be mixed

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void mixedNormalItalicsAndBoldText() { + assertThat(new Markdown().parse("This will _be_ __mixed__")) + .isEqualTo("

This will be mixed

"); } @Disabled("Remove to run test") @Test @DisplayName("with h1 header level") public void withH1HeaderLevel() { - String input = "# This will be an h1"; - String expected = "

This will be an h1

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("# This will be an h1")) + .isEqualTo("

This will be an h1

"); } @Disabled("Remove to run test") @Test @DisplayName("with h2 header level") public void withH2HeaderLevel() { - String input = "## This will be an h2"; - String expected = "

This will be an h2

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("## This will be an h2")) + .isEqualTo("

This will be an h2

"); } @Disabled("Remove to run test") @Test @DisplayName("with h3 header level") public void withH3HeaderLevel() { - String input = "### This will be an h3"; - String expected = "

This will be an h3

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("### This will be an h3")) + .isEqualTo("

This will be an h3

"); } @Disabled("Remove to run test") @Test @DisplayName("with h4 header level") public void withH4HeaderLevel() { - String input = "#### This will be an h4"; - String expected = "

This will be an h4

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("#### This will be an h4")) + .isEqualTo("

This will be an h4

"); } @Disabled("Remove to run test") @Test @DisplayName("with h5 header level") public void withH5HeaderLevel() { - String input = "##### This will be an h5"; - String expected = "
This will be an h5
"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("##### This will be an h5")) + .isEqualTo("
This will be an h5
"); } @Disabled("Remove to run test") @Test @DisplayName("with h6 header level") public void withH6HeaderLevel() { - String input = "###### This will be an h6"; - String expected = "
This will be an h6
"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("###### This will be an h6")) + .isEqualTo("
This will be an h6
"); } @Disabled("Remove to run test") @Test @DisplayName("h7 header level is a paragraph") public void h7HeaderLevelIsAParagraph() { - String input = "####### This will not be an h7"; - String expected = "

####### This will not be an h7

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("####### This will not be an h7")) + .isEqualTo("

####### This will not be an h7

"); } @Disabled("Remove to run test") @Test @DisplayName("unordered lists") public void unorderedLists() { - String input = "* Item 1\n* Item 2"; - String expected = "
  • Item 1
  • Item 2
"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + assertThat(new Markdown().parse("* Item 1\n* Item 2")) + .isEqualTo("
  • Item 1
  • Item 2
"); } @Disabled("Remove to run test") @Test @DisplayName("With a little bit of everything") - public void aLittleBitOfEverything() { - String input = "# Header!\n* __Bold Item__\n* _Italic Item_"; - String expected = "

Header!

  • Bold Item
  • Italic Item
"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void withALittleBitOfEverything() { + assertThat(new Markdown().parse("# Header!\n* __Bold Item__\n* _Italic Item_")) + .isEqualTo("

Header!

  • Bold " + + "Item
  • Italic Item
"); } @Disabled("Remove to run test") @Test @DisplayName("with markdown symbols in the header text that should not be interpreted") - public void markdownSymbolsInTheHeaderShouldNotBeInterpreted() { - String input = "# This is a header with # and * in the text"; - String expected = "

This is a header with # and * in the text

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void withMarkdownSymbolsInTheHeaderTextThatShouldNotBeInterpreted() { + assertThat(new Markdown().parse("# This is a header with # and * in the text")) + .isEqualTo("

This is a header with # and * in the text

"); } @Disabled("Remove to run test") @Test @DisplayName("with markdown symbols in the list item text that should not be interpreted") - public void markdownSymbolsInTheListItemTextShouldNotBeInterpreted() { - String input = "* Item 1 with a # in the text\n* Item 2 with * in the text"; - String expected = "
  • Item 1 with a # in the text
  • Item 2 with * in the text
"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void withMarkdownSymbolsInTheListItemTextThatShouldNotBeInterpreted() { + assertThat(new Markdown().parse("* Item 1 with a # in the text\n* Item 2 with * in the text")) + .isEqualTo("
  • Item 1 with a # in the text
  • Item 2 with * in the " + + "text
"); } @Disabled("Remove to run test") @Test @DisplayName("with markdown symbols in the paragraph text that should not be interpreted") - public void markdownSymbolsInTheParagraphTextShouldNotBeInterpreted() { - String input = "This is a paragraph with # and * in the text"; - String expected = "

This is a paragraph with # and * in the text

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void withMarkdownSymbolsInTheParagraphTextThatShouldNotBeInterpreted() { + assertThat(new Markdown().parse("This is a paragraph with # and * in the text")) + .isEqualTo("

This is a paragraph with # and * in the text

"); } @Disabled("Remove to run test") @Test @DisplayName("unordered lists close properly with preceding and following lines") - public void markdownUnorderedListsCloseProperlyWithPrecedingAndFollowingLines() { - String input = "# Start a list\n* Item 1\n* Item 2\nEnd a list"; - String expected = "

Start a list

  • Item 1
  • Item 2

End a list

"; - - assertThat(markdown.parse(input)).isEqualTo(expected); + public void unorderedListsCloseProperlyWithPrecedingAndFollowingLines() { + assertThat(new Markdown().parse("# Start a list\n* Item 1\n* Item 2\nEnd a list")) + .isEqualTo("

Start a list

  • Item 1
  • Item " + + "2

End a list

"); } } diff --git a/exercises/practice/matching-brackets/src/test/java/BracketCheckerTest.java b/exercises/practice/matching-brackets/src/test/java/BracketCheckerTest.java index 9051b388c..b1d992782 100644 --- a/exercises/practice/matching-brackets/src/test/java/BracketCheckerTest.java +++ b/exercises/practice/matching-brackets/src/test/java/BracketCheckerTest.java @@ -8,163 +8,162 @@ public class BracketCheckerTest { @Test @DisplayName("paired square brackets") - public void testPairedSquareBrackets() { - BracketChecker bracketChecker = new BracketChecker("[]"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void pairedSquareBrackets() { + assertThat(new BracketChecker("[]").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("empty string") - public void testEmptyString() { - BracketChecker bracketChecker = new BracketChecker(""); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void emptyString() { + assertThat(new BracketChecker("").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("unpaired brackets") - public void testUnpairedBrackets() { - BracketChecker bracketChecker = new BracketChecker("[["); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void unpairedBrackets() { + assertThat(new BracketChecker("[[").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("wrong ordered brackets") - public void testWrongOrderedBrackets() { - BracketChecker bracketChecker = new BracketChecker("}{"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void wrongOrderedBrackets() { + assertThat(new BracketChecker("}{").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("wrong closing bracket") - public void testWrongClosingBracket() { - BracketChecker bracketChecker = new BracketChecker("{]"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void wrongClosingBracket() { + assertThat(new BracketChecker("{]").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("paired with whitespace") - public void testPairedWithWhitespace() { - BracketChecker bracketChecker = new BracketChecker("{ }"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void pairedWithWhitespace() { + assertThat(new BracketChecker("{ }").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("partially paired brackets") - public void testPartiallyPairedBrackets() { - BracketChecker bracketChecker = new BracketChecker("{[])"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void partiallyPairedBrackets() { + assertThat(new BracketChecker("{[])").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("simple nested brackets") - public void testSimpleNestedBrackets() { - BracketChecker bracketChecker = new BracketChecker("{[]}"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void simpleNestedBrackets() { + assertThat(new BracketChecker("{[]}").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("several paired brackets") - public void testSeveralPairedBrackets() { - BracketChecker bracketChecker = new BracketChecker("{}[]"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void severalPairedBrackets() { + assertThat(new BracketChecker("{}[]").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("paired and nested brackets") - public void testPairedAndNestedBrackets() { - BracketChecker bracketChecker = new BracketChecker("([{}({}[])])"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void pairedAndNestedBrackets() { + assertThat(new BracketChecker("([{}({}[])])").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("unopened closing brackets") - public void testUnopenedClosingBracket() { - BracketChecker bracketChecker = new BracketChecker("{[)][]}"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void unopenedClosingBrackets() { + assertThat(new BracketChecker("{[)][]}").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("unpaired and nested brackets") - public void testUnpairedAndNestedBrackets() { - BracketChecker bracketChecker = new BracketChecker("([{])"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void unpairedAndNestedBrackets() { + assertThat(new BracketChecker("([{])").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("paired and wrong nested brackets") - public void testPairedAndWrongNestedBrackets() { - BracketChecker bracketChecker = new BracketChecker("[({]})"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void pairedAndWrongNestedBrackets() { + assertThat(new BracketChecker("[({]})").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("paired and wrong nested brackets but innermost are correct") - public void testPairedAndWrongNestedBracketsButInnermostAreCorrect() { - BracketChecker bracketChecker = new BracketChecker("[({}])"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void pairedAndWrongNestedBracketsButInnermostAreCorrect() { + assertThat(new BracketChecker("[({}])").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("paired and incomplete brackets") - public void testPairedAndIncompleteBrackets() { - BracketChecker bracketChecker = new BracketChecker("{}["); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void pairedAndIncompleteBrackets() { + assertThat(new BracketChecker("{}[").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("too many closing brackets") - public void testTooManyClosingBrackets() { - BracketChecker bracketChecker = new BracketChecker("[]]"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void tooManyClosingBrackets() { + assertThat(new BracketChecker("[]]").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("early unexpected brackets") - public void testEarlyUnexpectedBrackets() { - BracketChecker bracketChecker = new BracketChecker(")()"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void earlyUnexpectedBrackets() { + assertThat(new BracketChecker(")()").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("early mismatched brackets") - public void testEarlyMismatchedBrackets() { - BracketChecker bracketChecker = new BracketChecker("{)()"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isFalse(); + public void earlyMismatchedBrackets() { + assertThat(new BracketChecker("{)()").areBracketsMatchedAndNestedCorrectly()) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("math expression") - public void testMathExpression() { - BracketChecker bracketChecker = new BracketChecker("(((185 + 223.85) * 15) - 543)/2"); - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void mathExpression() { + assertThat(new BracketChecker("(((185 + 223.85) * 15) - 543)/2").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("complex latex expression") - public void testComplexLatexExpression() { - BracketChecker bracketChecker = new BracketChecker( - "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)"); - - assertThat(bracketChecker.areBracketsMatchedAndNestedCorrectly()).isTrue(); + public void complexLatexExpression() { + assertThat(new BracketChecker("\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} " + + "&... x^2 \\end{array}\\right)").areBracketsMatchedAndNestedCorrectly()) + .isTrue(); } } diff --git a/exercises/practice/matrix/src/test/java/MatrixTest.java b/exercises/practice/matrix/src/test/java/MatrixTest.java index 5eb9ccfb4..7a68967e3 100644 --- a/exercises/practice/matrix/src/test/java/MatrixTest.java +++ b/exercises/practice/matrix/src/test/java/MatrixTest.java @@ -8,104 +8,65 @@ public class MatrixTest { @Test @DisplayName("extract row from one number matrix") - public void extractRowFromOneNumberMatrixTest() { - String matrixAsString = "1"; - int rowIndex = 1; - int[] expectedRow = {1}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getRow(rowIndex)).isEqualTo(expectedRow); + public void extractRowFromOneNumberMatrix() { + assertThat(new Matrix("1").getRow(1)) + .isEqualTo(new int[]{1}); } @Disabled("Remove to run test") @Test @DisplayName("can extract row") - public void extractRowFromMatrixTest() { - String matrixAsString = "1 2\n3 4"; - int rowIndex = 2; - int[] expectedRow = {3, 4}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getRow(rowIndex)).isEqualTo(expectedRow); + public void canExtractRow() { + assertThat(new Matrix("1 2\n3 4").getRow(2)) + .isEqualTo(new int[]{3, 4}); } @Disabled("Remove to run test") @Test @DisplayName("extract row where numbers have different widths") - public void extractRowFromDiffWidthsMatrixTest() { - String matrixAsString = "1 2\n10 20"; - int rowIndex = 2; - int[] expectedRow = {10, 20}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getRow(rowIndex)).isEqualTo(expectedRow); + public void extractRowWhereNumbersHaveDifferentWidths() { + assertThat(new Matrix("1 2\n10 20").getRow(2)) + .isEqualTo(new int[]{10, 20}); } @Disabled("Remove to run test") @Test @DisplayName("can extract row from non-square matrix with no corresponding column") - public void extractRowFromNonSquareMatrixTest() { - String matrixAsString = "1 2 3\n4 5 6\n7 8 9\n8 7 6"; - int rowIndex = 4; - int[] expectedRow = {8, 7, 6}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getRow(rowIndex)).isEqualTo(expectedRow); + public void canExtractRowFromNonSquareMatrixWithNoCorrespondingColumn() { + assertThat(new Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6").getRow(4)) + .isEqualTo(new int[]{8, 7, 6}); } @Disabled("Remove to run test") @Test @DisplayName("extract column from one number matrix") - public void extractColumnFromOneNumberMatrixTest() { - String matrixAsString = "1"; - int columnIndex = 1; - int[] expectedColumn = {1}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getColumn(columnIndex)).isEqualTo(expectedColumn); + public void extractColumnFromOneNumberMatrix() { + assertThat(new Matrix("1").getColumn(1)) + .isEqualTo(new int[]{1}); } @Disabled("Remove to run test") @Test @DisplayName("can extract column") - public void extractColumnMatrixTest() { - String matrixAsString = "1 2 3\n4 5 6\n7 8 9"; - int columnIndex = 3; - int[] expectedColumn = {3, 6, 9}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getColumn(columnIndex)).isEqualTo(expectedColumn); + public void canExtractColumn() { + assertThat(new Matrix("1 2 3\n4 5 6\n7 8 9").getColumn(3)) + .isEqualTo(new int[]{3, 6, 9}); } @Disabled("Remove to run test") @Test @DisplayName("can extract column from non-square matrix with no corresponding row") - public void extractColumnFromNonSquareMatrixTest() { - String matrixAsString = "1 2 3 4\n5 6 7 8\n9 8 7 6"; - int columnIndex = 4; - int[] expectedColumn = {4, 8, 6}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getColumn(columnIndex)).isEqualTo(expectedColumn); + public void canExtractColumnFromNonSquareMatrixWithNoCorrespondingRow() { + assertThat(new Matrix("1 2 3 4\n5 6 7 8\n9 8 7 6").getColumn(4)) + .isEqualTo(new int[]{4, 8, 6}); } @Disabled("Remove to run test") @Test @DisplayName("extract column where numbers have different widths") - public void extractColumnFromDiffWidthsMatrixTest() { - String matrixAsString = "89 1903 3\n18 3 1\n9 4 800"; - int columnIndex = 2; - int[] expectedColumn = {1903, 3, 4}; - - Matrix matrix = new Matrix(matrixAsString); - - assertThat(matrix.getColumn(columnIndex)).isEqualTo(expectedColumn); + public void extractColumnWhereNumbersHaveDifferentWidths() { + assertThat(new Matrix("89 1903 3\n18 3 1\n9 4 800").getColumn(2)) + .isEqualTo(new int[]{1903, 3, 4}); } + } diff --git a/exercises/practice/meetup/src/test/java/MeetupTest.java b/exercises/practice/meetup/src/test/java/MeetupTest.java index 193eaa9ea..96dbdb9ae 100644 --- a/exercises/practice/meetup/src/test/java/MeetupTest.java +++ b/exercises/practice/meetup/src/test/java/MeetupTest.java @@ -11,855 +11,951 @@ public class MeetupTest { @Test @DisplayName("when teenth Monday is the 13th, the first day of the teenth week") - public void testMonteenthOfMay2013() { + public void whenTeenthMondayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 5, 13); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Monday is the 19th, the last day of the teenth week") - public void testMonteenthOfAugust2013() { + public void whenTeenthMondayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 8, 19); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Monday is some day in the middle of the teenth week") - public void testMonteenthOfSeptember2013() { + public void whenTeenthMondayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 9, 16); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Tuesday is the 19th, the last day of the teenth week") - public void testTuesteenthOfMarch2013() { + public void whenTeenthTuesdayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 3, 19); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Tuesday is some day in the middle of the teenth week") - public void testTuesteenthOfApril2013() { + public void whenTeenthTuesdayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 4, 16); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Tuesday is the 13th, the first day of the teenth week") - public void testTuesteenthOfAugust2013() { + public void whenTeenthTuesdayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 8, 13); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Wednesday is some day in the middle of the teenth week") - public void testWednesteenthOfJanuary2013() { + public void whenTeenthWednesdayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 1, 16); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Wednesday is the 13th, the first day of the teenth week") - public void testWednesteenthOfFebruary2013() { + public void whenTeenthWednesdayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 2, 13); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Wednesday is the 19th, the last day of the teenth week") - public void testWednesteenthOfJune2013() { + public void whenTeenthWednesdayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 6, 19); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Thursday is some day in the middle of the teenth week") - public void testThursteenthOfMay2013() { + public void whenTeenthThursdayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 5, 16); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Thursday is the 13th, the first day of the teenth week") - public void testThursteenthOfJune2013() { + public void whenTeenthThursdayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 6, 13); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Thursday is the 19th, the last day of the teenth week") - public void testThursteenthOfSeptember2013() { + public void whenTeenthThursdayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 9, 19); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Friday is the 19th, the last day of the teenth week") - public void testFriteenthOfApril2013() { + public void whenTeenthFridayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 4, 19); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Friday is some day in the middle of the teenth week") - public void testFriteenthOfAugust2013() { + public void whenTeenthFridayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 8, 16); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Friday is the 13th, the first day of the teenth week") - public void testFriteenthOfSeptember2013() { + public void whenTeenthFridayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 9, 13); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Saturday is some day in the middle of the teenth week") - public void testSaturteenthOfFebruary2013() { + public void whenTeenthSaturdayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 2, 16); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Saturday is the 13th, the first day of the teenth week") - public void testSaturteenthOfApril2013() { + public void whenTeenthSaturdayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 4, 13); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Saturday is the 19th, the last day of the teenth week") - public void testSaturteenthOfOctober2013() { + public void whenTeenthSaturdayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 10, 19); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Sunday is the 19th, the last day of the teenth week") - public void testSunteenthOfMay2013() { + public void whenTeenthSundayIsThe19thTheLastDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 5, 19); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Sunday is some day in the middle of the teenth week") - public void testSunteenthOfJune2013() { + public void whenTeenthSundayIsSomeDayInTheMiddleOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 6, 16); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when teenth Sunday is the 13th, the first day of the teenth week") - public void testSunteenthOfOctober2013() { + public void whenTeenthSundayIsThe13thTheFirstDayOfTheTeenthWeek() { LocalDate expected = LocalDate.of(2013, 10, 13); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.TEENTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Monday is some day in the middle of the first week") - public void testFirstMondayOfMarch2013() { + public void whenFirstMondayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 3, 4); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Monday is the 1st, the first day of the first week") - public void testFirstMondayOfApril2013() { + public void whenFirstMondayIsThe1stTheFirstDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 4, 1); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Tuesday is the 7th, the last day of the first week") - public void testFirstTuesdayOfMay2013() { + public void whenFirstTuesdayIsThe7thTheLastDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 5, 7); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Tuesday is some day in the middle of the first week") - public void testFirstTuesdayOfJune2013() { + public void whenFirstTuesdayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 6, 4); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Wednesday is some day in the middle of the first week") - public void testFirstWednesdayOfJuly2013() { + public void whenFirstWednesdayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 7, 3); Meetup meetup = new Meetup(7, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Wednesday is the 7th, the last day of the first week") - public void testFirstWednesdayOfAugust2013() { + public void whenFirstWednesdayIsThe7thTheLastDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 8, 7); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("when first Thursday is some day in the middle of the first wee") - public void testFirstThursdayOfSeptember2013() { + @DisplayName("when first Thursday is some day in the middle of the first week") + public void whenFirstThursdayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 9, 5); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Thursday is another day in the middle of the first week") - public void testFirstThursdayOfOctober2013() { + public void whenFirstThursdayIsAnotherDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 10, 3); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Friday is the 1st, the first day of the first week") - public void testFirstFridayOfNovember2013() { + public void whenFirstFridayIsThe1stTheFirstDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 11, 1); Meetup meetup = new Meetup(11, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Friday is some day in the middle of the first week") - public void testFirstFridayOfDecember2013() { + public void whenFirstFridayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 12, 6); Meetup meetup = new Meetup(12, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Saturday is some day in the middle of the first week") - public void testFirstSaturdayOfJanuary2013() { + public void whenFirstSaturdayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 1, 5); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Saturday is another day in the middle of the first week") - public void testFirstSaturdayOfFebruary2013() { + public void whenFirstSaturdayIsAnotherDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 2, 2); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Sunday is some day in the middle of the first week") - public void testFirstSundayOfMarch2013() { + public void whenFirstSundayIsSomeDayInTheMiddleOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 3, 3); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Sunday is the 7th, the last day of the first week") - public void testFirstSundayOfApril2013() { + public void whenFirstSundayIsThe7thTheLastDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2013, 4, 7); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Monday is some day in the middle of the second week") - public void testSecondMondayOfMarch2013() { + public void whenSecondMondayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 3, 11); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Monday is the 8th, the first day of the second week") - public void testSecondMondayOfApril2013() { + public void whenSecondMondayIsThe8thTheFirstDayOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 4, 8); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Tuesday is the 14th, the last day of the second week") - public void testSecondTuesdayOfMay2013() { + public void whenSecondTuesdayIsThe14thTheLastDayOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 5, 14); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Tuesday is some day in the middle of the second week") - public void testSecondTuesdayOfJune2013() { + public void whenSecondTuesdayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 6, 11); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Wednesday is some day in the middle of the second week") - public void testSecondWednesdayOfJuly2013() { + public void whenSecondWednesdayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 7, 10); Meetup meetup = new Meetup(7, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Wednesday is the 14th, the last day of the second week") - public void testSecondWednesdayOfAugust2013() { + public void whenSecondWednesdayIsThe14thTheLastDayOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 8, 14); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Thursday is some day in the middle of the second week") - public void testSecondThursdayOfSeptember2013() { + public void whenSecondThursdayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 9, 12); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Thursday is another day in the middle of the second week") - public void testSecondThursdayOfOctober2013() { + public void whenSecondThursdayIsAnotherDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 10, 10); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Friday is the 8th, the first day of the second week") - public void testSecondFridayOfNovember2013() { + public void whenSecondFridayIsThe8thTheFirstDayOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 11, 8); Meetup meetup = new Meetup(11, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Friday is some day in the middle of the second week") - public void testSecondFridayOfDecember2013() { + public void whenSecondFridayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 12, 13); Meetup meetup = new Meetup(12, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Saturday is some day in the middle of the second week") - public void testSecondSaturdayOfJanuary2013() { + public void whenSecondSaturdayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 1, 12); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Saturday is another day in the middle of the second week") - public void testSecondSaturdayOfFebruary2013() { + public void whenSecondSaturdayIsAnotherDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 2, 9); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Sunday is some day in the middle of the second week") - public void testSecondSundayOfMarch2013() { + public void whenSecondSundayIsSomeDayInTheMiddleOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 3, 10); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when second Sunday is the 14th, the last day of the second week") - public void testSecondSundayOfApril2013() { + public void whenSecondSundayIsThe14thTheLastDayOfTheSecondWeek() { LocalDate expected = LocalDate.of(2013, 4, 14); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.SECOND)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Monday is some day in the middle of the third week") - public void testThirdMondayOfMarch2013() { + public void whenThirdMondayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 3, 18); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Monday is the 15th, the first day of the third week") - public void testThirdMondayOfApril2013() { + public void whenThirdMondayIsThe15thTheFirstDayOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 4, 15); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Tuesday is the 21st, the last day of the third week") - public void testThirdTuesdayOfMay2013() { + public void whenThirdTuesdayIsThe21stTheLastDayOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 5, 21); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Tuesday is some day in the middle of the third week") - public void testThirdTuesdayOfJune2013() { + public void whenThirdTuesdayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 6, 18); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Wednesday is some day in the middle of the third week") - public void testThirdWednesdayOfJuly2013() { + public void whenThirdWednesdayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 7, 17); Meetup meetup = new Meetup(7, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Wednesday is the 21st, the last day of the third week") - public void testThirdWednesdayOfAugust2013() { + public void whenThirdWednesdayIsThe21stTheLastDayOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 8, 21); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Thursday is some day in the middle of the third week") - public void testThirdThursdayOfSeptember2013() { + public void whenThirdThursdayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 9, 19); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Thursday is another day in the middle of the third week") - public void testThirdThursdayOfOctober2013() { + public void whenThirdThursdayIsAnotherDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 10, 17); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Friday is the 15th, the first day of the third week") - public void testThirdFridayOfNovember2013() { + public void whenThirdFridayIsThe15thTheFirstDayOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 11, 15); Meetup meetup = new Meetup(11, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Friday is some day in the middle of the third week") - public void testThirdFridayOfDecember2013() { + public void whenThirdFridayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 12, 20); Meetup meetup = new Meetup(12, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Saturday is some day in the middle of the third week") - public void testThirdSaturdayOfJanuary2013() { + public void whenThirdSaturdayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 1, 19); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Saturday is another day in the middle of the third week") - public void testThirdSaturdayOfFebruary2013() { + public void whenThirdSaturdayIsAnotherDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 2, 16); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Sunday is some day in the middle of the third week") - public void testThirdSundayOfMarch2013() { + public void whenThirdSundayIsSomeDayInTheMiddleOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 3, 17); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when third Sunday is the 21st, the last day of the third week") - public void testThirdSundayOfApril2013() { + public void whenThirdSundayIsThe21stTheLastDayOfTheThirdWeek() { LocalDate expected = LocalDate.of(2013, 4, 21); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.THIRD)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Monday is some day in the middle of the fourth week") - public void testFourthMondayOfMarch2013() { + public void whenFourthMondayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 3, 25); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Monday is the 22nd, the first day of the fourth week") - public void testFourthMondayOfApril2013() { + public void whenFourthMondayIsThe22ndTheFirstDayOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 4, 22); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Tuesday is the 28th, the last day of the fourth week") - public void testFourthTuesdayOfMay2013() { + public void whenFourthTuesdayIsThe28thTheLastDayOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 5, 28); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Tuesday is some day in the middle of the fourth week") - public void testFourthTuesdayOfJune2013() { + public void whenFourthTuesdayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 6, 25); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Wednesday is some day in the middle of the fourth week") - public void testFourthWednesdayOfJuly2013() { + public void whenFourthWednesdayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 7, 24); Meetup meetup = new Meetup(7, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Wednesday is the 28th, the last day of the fourth week") - public void testFourthWednesdayOfAugust2013() { + public void whenFourthWednesdayIsThe28thTheLastDayOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 8, 28); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Thursday is some day in the middle of the fourth week") - public void testFourthThursdayOfSeptember2013() { + public void whenFourthThursdayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 9, 26); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Thursday is another day in the middle of the fourth week") - public void testFourthThursdayOfOctober2013() { + public void whenFourthThursdayIsAnotherDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 10, 24); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Friday is the 22nd, the first day of the fourth week") - public void testFourthFridayOfNovember2013() { + public void whenFourthFridayIsThe22ndTheFirstDayOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 11, 22); Meetup meetup = new Meetup(11, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Friday is some day in the middle of the fourth week") - public void testFourthFridayOfDecember2013() { + public void whenFourthFridayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 12, 27); Meetup meetup = new Meetup(12, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Saturday is some day in the middle of the fourth week") - public void testFourthSaturdayOfJanuary2013() { + public void whenFourthSaturdayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 1, 26); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Saturday is another day in the middle of the fourth week") - public void testFourthSaturdayOfFebruary2013() { + public void whenFourthSaturdayIsAnotherDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 2, 23); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Sunday is some day in the middle of the fourth week") - public void testFourthSundayOfMarch2013() { + public void whenFourthSundayIsSomeDayInTheMiddleOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 3, 24); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when fourth Sunday is the 28th, the last day of the fourth week") - public void testFourthSundayOfApril2013() { + public void whenFourthSundayIsThe28thTheLastDayOfTheFourthWeek() { LocalDate expected = LocalDate.of(2013, 4, 28); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.FOURTH)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Monday in a month with four Mondays") - public void testLastMondayOfMarch2013() { + public void lastMondayInAMonthWithFourMondays() { LocalDate expected = LocalDate.of(2013, 3, 25); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Monday in a month with five Mondays") - public void testLastMondayOfApril2013() { + public void lastMondayInAMonthWithFiveMondays() { LocalDate expected = LocalDate.of(2013, 4, 29); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.MONDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Tuesday in a month with four Tuesdays") - public void testLastTuesdayOfMay2013() { + public void lastTuesdayInAMonthWithFourTuesdays() { LocalDate expected = LocalDate.of(2013, 5, 28); Meetup meetup = new Meetup(5, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Tuesday in another month with four Tuesdays") - public void testLastTuesdayOfJune2013() { + public void lastTuesdayInAnotherMonthWithFourTuesdays() { LocalDate expected = LocalDate.of(2013, 6, 25); Meetup meetup = new Meetup(6, 2013); - assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.TUESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Wednesday in a month with five Wednesdays") - public void testLastWednesdayOfJuly2013() { + public void lastWednesdayInAMonthWithFiveWednesdays() { LocalDate expected = LocalDate.of(2013, 7, 31); Meetup meetup = new Meetup(7, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Wednesday in a month with four Wednesdays") - public void testLastWednesdayOfAugust2013() { + public void lastWednesdayInAMonthWithFourWednesdays() { LocalDate expected = LocalDate.of(2013, 8, 28); Meetup meetup = new Meetup(8, 2013); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Thursday in a month with four Thursdays") - public void testLastThursdayOfSeptember2013() { + public void lastThursdayInAMonthWithFourThursdays() { LocalDate expected = LocalDate.of(2013, 9, 26); Meetup meetup = new Meetup(9, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Thursday in a month with five Thursdays") - public void testLastThursdayOfOctober2013() { + public void lastThursdayInAMonthWithFiveThursdays() { LocalDate expected = LocalDate.of(2013, 10, 31); Meetup meetup = new Meetup(10, 2013); - assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.THURSDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Friday in a month with five Fridays") - public void testLastFridayOfNovember2013() { + public void lastFridayInAMonthWithFiveFridays() { LocalDate expected = LocalDate.of(2013, 11, 29); Meetup meetup = new Meetup(11, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Friday in a month with four Fridays") - public void testLastFridayOfDecember2013() { + public void lastFridayInAMonthWithFourFridays() { LocalDate expected = LocalDate.of(2013, 12, 27); Meetup meetup = new Meetup(12, 2013); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Saturday in a month with four Saturdays") - public void testLastSaturdayOfJanuary2013() { + public void lastSaturdayInAMonthWithFourSaturdays() { LocalDate expected = LocalDate.of(2013, 1, 26); Meetup meetup = new Meetup(1, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Saturday in another month with four Saturdays") - public void testLastSaturdayOfFebruary2013() { + public void lastSaturdayInAnotherMonthWithFourSaturdays() { LocalDate expected = LocalDate.of(2013, 2, 23); Meetup meetup = new Meetup(2, 2013); - assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SATURDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Sunday in a month with five Sundays") - public void testLastSundayOfMarch2013() { + public void lastSundayInAMonthWithFiveSundays() { LocalDate expected = LocalDate.of(2013, 3, 31); Meetup meetup = new Meetup(3, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Sunday in a month with four Sundays") - public void testLastSundayOfApril2013() { + public void lastSundayInAMonthWithFourSundays() { LocalDate expected = LocalDate.of(2013, 4, 28); Meetup meetup = new Meetup(4, 2013); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when last Wednesday in February in a leap year is the 29th") - public void testLastWednesdayOfFebruary2012() { + public void whenLastWednesdayInFebruaryInALeapYearIsThe29th() { LocalDate expected = LocalDate.of(2012, 2, 29); Meetup meetup = new Meetup(2, 2012); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("last Wednesday in December that is also the last day of the year") - public void testLastWednesdayOfDecember2014() { + public void lastWednesdayInDecemberThatIsAlsoTheLastDayOfTheYear() { LocalDate expected = LocalDate.of(2014, 12, 31); Meetup meetup = new Meetup(12, 2014); - assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.WEDNESDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when last Sunday in February in a non-leap year is not the 29th") - public void testLastSundayOfFebruary2015() { + public void whenLastSundayInFebruaryInANonLeapYearIsNotThe29th() { LocalDate expected = LocalDate.of(2015, 2, 22); Meetup meetup = new Meetup(2, 2015); - assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.SUNDAY, MeetupSchedule.LAST)) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("when first Friday is the 7th, the last day of the first week") - public void testFirstFridayOfDecember2012() { + public void whenFirstFridayIsThe7thTheLastDayOfTheFirstWeek() { LocalDate expected = LocalDate.of(2012, 12, 7); Meetup meetup = new Meetup(12, 2012); - assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)).isEqualTo(expected); + assertThat(meetup.day(DayOfWeek.FRIDAY, MeetupSchedule.FIRST)) + .isEqualTo(expected); } + } diff --git a/exercises/practice/micro-blog/src/test/java/MicroBlogTest.java b/exercises/practice/micro-blog/src/test/java/MicroBlogTest.java index 1b44d5a78..6bb1bd086 100644 --- a/exercises/practice/micro-blog/src/test/java/MicroBlogTest.java +++ b/exercises/practice/micro-blog/src/test/java/MicroBlogTest.java @@ -6,100 +6,99 @@ public class MicroBlogTest { - private final MicroBlog microBlog = new MicroBlog(); - @Test @DisplayName("English language short") public void englishLanguageShort() { - String expected = "Hi"; - assertThat(microBlog.truncate("Hi")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("Hi")) + .isEqualTo("Hi"); } @Disabled("Remove to run test") @Test @DisplayName("English language long") public void englishLanguageLong() { - String expected = "Hello"; - assertThat(microBlog.truncate("Hello there")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("Hello there")) + .isEqualTo("Hello"); } - + @Disabled("Remove to run test") @Test @DisplayName("German language short (broth)") public void germanLanguageShortBroth() { - String expected = "brühe"; - assertThat(microBlog.truncate("brühe")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("brühe")) + .isEqualTo("brühe"); } @Disabled("Remove to run test") @Test @DisplayName("German language long (bear carpet → beards)") - public void germanLanguageLongBearCarpetToBeards() { - String expected = "Bärte"; - assertThat(microBlog.truncate("Bärteppich")).isEqualTo(expected); + public void germanLanguageLongBearCarpetBeards() { + assertThat(new MicroBlog().truncate("Bärteppich")) + .isEqualTo("Bärte"); } - + @Disabled("Remove to run test") @Test @DisplayName("Bulgarian language short (good)") public void bulgarianLanguageShortGood() { - String expected = "Добър"; - assertThat(microBlog.truncate("Добър")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("Добър")) + .isEqualTo("Добър"); } @Disabled("Remove to run test") @Test @DisplayName("Greek language short (health)") public void greekLanguageShortHealth() { - String expected = "υγειά"; - assertThat(microBlog.truncate("υγειά")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("υγειά")) + .isEqualTo("υγειά"); } - + @Disabled("Remove to run test") @Test @DisplayName("Maths short") public void mathsShort() { - String expected = "a=πr²"; - assertThat(microBlog.truncate("a=πr²")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("a=πr²")) + .isEqualTo("a=πr²"); } @Disabled("Remove to run test") @Test @DisplayName("Maths long") public void mathsLong() { - String expected = "∅⊊ℕ⊊ℤ"; - assertThat(microBlog.truncate("∅⊊ℕ⊊ℤ⊊ℚ⊊ℝ⊊ℂ")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("∅⊊ℕ⊊ℤ⊊ℚ⊊ℝ⊊ℂ")) + .isEqualTo("∅⊊ℕ⊊ℤ"); } - + @Disabled("Remove to run test") @Test @DisplayName("English and emoji short") public void englishAndEmojiShort() { - String expected = "Fly 🛫"; - assertThat(microBlog.truncate("Fly 🛫")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("Fly 🛫")) + .isEqualTo("Fly 🛫"); } - + @Disabled("Remove to run test") @Test @DisplayName("Emoji short") public void emojiShort() { - String expected = "💇"; - assertThat(microBlog.truncate("💇")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("💇")) + .isEqualTo("💇"); } - + @Disabled("Remove to run test") @Test @DisplayName("Emoji long") public void emojiLong() { - String expected = "❄🌡🤧🤒🏥"; - assertThat(microBlog.truncate("❄🌡🤧🤒🏥🕰😀")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("❄🌡🤧🤒🏥🕰😀")) + .isEqualTo("❄🌡🤧🤒🏥"); } - + @Disabled("Remove to run test") @Test @DisplayName("Royal Flush?") public void royalFlush() { - String expected = "🃎🂸🃅🃋🃍"; - assertThat(microBlog.truncate("🃎🂸🃅🃋🃍🃁🃊")).isEqualTo(expected); + assertThat(new MicroBlog().truncate("🃎🂸🃅🃋🃍🃁🃊")) + .isEqualTo("🃎🂸🃅🃋🃍"); } + } diff --git a/exercises/practice/nth-prime/src/test/java/PrimeCalculatorTest.java b/exercises/practice/nth-prime/src/test/java/PrimeCalculatorTest.java index 10d0bcf29..41e36c402 100644 --- a/exercises/practice/nth-prime/src/test/java/PrimeCalculatorTest.java +++ b/exercises/practice/nth-prime/src/test/java/PrimeCalculatorTest.java @@ -1,47 +1,49 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class PrimeCalculatorTest { +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - private PrimeCalculator primeCalculator = new PrimeCalculator(); +public class PrimeCalculatorTest { @Test @DisplayName("first prime") - public void testFirstPrime() { - assertThat(primeCalculator.nth(1)).isEqualTo(2); + public void firstPrime() { + assertThat(new PrimeCalculator().nth(1)) + .isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("second prime") - public void testSecondPrime() { - assertThat(primeCalculator.nth(2)).isEqualTo(3); + public void secondPrime() { + assertThat(new PrimeCalculator().nth(2)) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("sixth prime") - public void testSixthPrime() { - assertThat(primeCalculator.nth(6)).isEqualTo(13); + public void sixthPrime() { + assertThat(new PrimeCalculator().nth(6)) + .isEqualTo(13); } @Disabled("Remove to run test") @Test @DisplayName("big prime") - public void testBigPrime() { - assertThat(primeCalculator.nth(10001)).isEqualTo(104743); + public void bigPrime() { + assertThat(new PrimeCalculator().nth(10001)) + .isEqualTo(104743); } @Disabled("Remove to run test") @Test @DisplayName("there is no zeroth prime") - public void testUndefinedPrime() { + public void thereIsNoZerothPrime() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> primeCalculator.nth(0)); + .isThrownBy(() -> new PrimeCalculator().nth(0)); } } diff --git a/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java b/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java index d5938268a..3a8fc5dea 100644 --- a/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java +++ b/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java @@ -11,53 +11,71 @@ public class NucleotideCounterTest { @Test @DisplayName("empty strand") - public void testEmptyDnaStringHasNoNucleotides() { - NucleotideCounter nucleotideCounter = new NucleotideCounter(""); + public void emptyStrand() { + + NucleotideCounter counter = new NucleotideCounter( + ""); + + assertThat(counter.nucleotideCounts()) + .containsExactlyInAnyOrderEntriesOf( + Map.of('A', 0, 'C', 0, + 'G', 0, 'T', 0)); - assertThat(nucleotideCounter.nucleotideCounts()) - .containsExactlyInAnyOrderEntriesOf( - Map.of('A', 0, 'C', 0, 'G', 0, 'T', 0)); } @Disabled("Remove to run test") @Test @DisplayName("can count one nucleotide in single-character input") - public void testDnaStringHasOneNucleotide() { - NucleotideCounter nucleotideCounter = new NucleotideCounter("G"); + public void canCountOneNucleotideInSingleCharacterInput() { + + NucleotideCounter counter = new NucleotideCounter( + "G"); + + assertThat(counter.nucleotideCounts()) + .containsExactlyInAnyOrderEntriesOf( + Map.of('A', 0, 'C', 0, + 'G', 1, 'T', 0)); - assertThat(nucleotideCounter.nucleotideCounts()) - .containsExactlyInAnyOrderEntriesOf( - Map.of('A', 0, 'C', 0, 'G', 1, 'T', 0)); } @Disabled("Remove to run test") @Test @DisplayName("strand with repeated nucleotide") - public void testRepetitiveSequenceWithOnlyGuanine() { - NucleotideCounter nucleotideCounter = new NucleotideCounter("GGGGGGG"); + public void strandWithRepeatedNucleotide() { + + NucleotideCounter counter = new NucleotideCounter( + "GGGGGGG"); + + assertThat(counter.nucleotideCounts()) + .containsExactlyInAnyOrderEntriesOf( + Map.of('A', 0, 'C', 0, + 'G', 7, 'T', 0)); - assertThat(nucleotideCounter.nucleotideCounts()) - .containsExactlyInAnyOrderEntriesOf( - Map.of('A', 0, 'C', 0, 'G', 7, 'T', 0)); } @Disabled("Remove to run test") @Test @DisplayName("strand with multiple nucleotides") - public void testDnaStringHasMultipleNucleotide() { - NucleotideCounter nucleotideCounter - = new NucleotideCounter("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"); + public void strandWithMultipleNucleotides() { + + NucleotideCounter counter = new NucleotideCounter( + "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"); + + assertThat(counter.nucleotideCounts()) + .containsExactlyInAnyOrderEntriesOf( + Map.of('A', 20, 'C', 12, + 'G', 17, 'T', 21)); - assertThat(nucleotideCounter.nucleotideCounts()) - .containsExactlyInAnyOrderEntriesOf( - Map.of('A', 20, 'C', 12, 'G', 17, 'T', 21)); } @Disabled("Remove to run test") @Test @DisplayName("strand with invalid nucleotides") - public void testDnaStringHasInvalidNucleotides() { + public void strandWithInvalidNucleotides() { + assertThatThrownBy(() -> new NucleotideCounter("AGXXACT")) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); + } + } diff --git a/exercises/practice/ocr-numbers/src/test/java/OpticalCharacterReaderTest.java b/exercises/practice/ocr-numbers/src/test/java/OpticalCharacterReaderTest.java index 6cc079c23..5bb2c22d4 100644 --- a/exercises/practice/ocr-numbers/src/test/java/OpticalCharacterReaderTest.java +++ b/exercises/practice/ocr-numbers/src/test/java/OpticalCharacterReaderTest.java @@ -1,248 +1,160 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class OpticalCharacterReaderTest { @Test @DisplayName("Recognizes 0") - public void testReaderRecognizesSingle0() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - "| |", - "|_|", - " " - )); - - assertThat(parsedInput).isEqualTo("0"); - + public void recognizes0() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", "| |", "|_|", " "))) + .isEqualTo("0"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 1") - public void testReaderRecognizesSingle1() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " ", - " |", - " |", - " " - )); - - assertThat(parsedInput).isEqualTo("1"); + public void recognizes1() { + assertThat(new OpticalCharacterReader().parse(List.of(" ", " |", " |", " "))) + .isEqualTo("1"); } @Disabled("Remove to run test") @Test @DisplayName("Unreadable but correctly sized inputs return ?") - public void testReaderReturnsQuestionMarkForUnreadableButCorrectlySizedInput() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " ", - " _", - " |", - " " - )); - - assertThat(parsedInput).isEqualTo("?"); + public void unreadableButCorrectlySizedInputsReturn() { + assertThat(new OpticalCharacterReader().parse(List.of(" ", " _", " |", " "))) + .isEqualTo("?"); } @Disabled("Remove to run test") @Test @DisplayName("Input with a number of lines that is not a multiple of four raises an error") - public void testReaderThrowsExceptionWhenNumberOfInputLinesIsNotAMultipleOf4() { - + public void inputWithANumberOfLinesThatIsNotAMultipleOfFourRaisesAnError() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new OpticalCharacterReader() - .parse( - Arrays.asList( - " _ ", - "| |", - " "))) + .isThrownBy(() -> new OpticalCharacterReader().parse(List.of(" _ ", "| |", " "))) .withMessage("Number of input rows must be a positive multiple of 4"); } @Disabled("Remove to run test") @Test @DisplayName("Input with a number of columns that is not a multiple of three raises an error") - public void testReaderThrowsExceptionWhenNumberOfInputColumnsIsNotAMultipleOf3() { - - + public void inputWithANumberOfColumnsThatIsNotAMultipleOfThreeRaisesAnError() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new OpticalCharacterReader() - .parse( - Arrays.asList( - " ", - " |", - " |", - " "))) + .isThrownBy(() -> new OpticalCharacterReader().parse(List.of(" ", " |", " |", " "))) .withMessage("Number of input columns must be a positive multiple of 3"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 110101100") - public void testReaderRecognizesBinarySequence110101100() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( + public void recognizes110101100() { + assertThat(new OpticalCharacterReader().parse(List.of( " _ _ _ _ ", " | || | || | | || || |", " | ||_| ||_| | ||_||_|", - " " - )); - - assertThat(parsedInput).isEqualTo("110101100"); + " "))) + .isEqualTo("110101100"); } @Disabled("Remove to run test") @Test @DisplayName("Garbled numbers in a string are replaced with ?") - public void testReaderReplacesUnreadableDigitsWithQuestionMarksWithinSequence() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( + public void garbledNumbersInAStringAreReplacedWith() { + assertThat(new OpticalCharacterReader().parse(List.of( " _ _ _ ", " | || | || | || || |", " | | _| ||_| | ||_||_|", - " " - )); - - - assertThat(parsedInput).isEqualTo("11?10?1?0"); + " "))) + .isEqualTo("11?10?1?0"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 2") - public void testReaderRecognizesSingle2() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - " _|", - "|_ ", - " " - )); - - assertThat(parsedInput).isEqualTo("2"); + public void recognizes2() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", " _|", "|_ ", " "))) + .isEqualTo("2"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 3") - public void testReaderRecognizesSingle3() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - " _|", - " _|", - " " - )); - - assertThat(parsedInput).isEqualTo("3"); + public void recognizes3() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", " _|", " _|", " "))) + .isEqualTo("3"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 4") - public void testReaderRecognizesSingle4() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " ", - "|_|", - " |", - " " - )); - - assertThat(parsedInput).isEqualTo("4"); + public void recognizes4() { + assertThat(new OpticalCharacterReader().parse(List.of(" ", "|_|", " |", " "))) + .isEqualTo("4"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 5") - public void testReaderRecognizesSingle5() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - "|_ ", - " _|", - " " - )); - - assertThat(parsedInput).isEqualTo("5"); + public void recognizes5() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", "|_ ", " _|", " "))) + .isEqualTo("5"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 6") - public void testReaderRecognizesSingle6() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - "|_ ", - "|_|", - " " - )); - - assertThat(parsedInput).isEqualTo("6"); + public void recognizes6() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", "|_ ", "|_|", " "))) + .isEqualTo("6"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 7") - public void testReaderRecognizesSingle7() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - " |", - " |", - " " - )); - - assertThat(parsedInput).isEqualTo("7"); + public void recognizes7() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", " |", " |", " "))) + .isEqualTo("7"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 8") - public void testReaderRecognizesSingle8() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - "|_|", - "|_|", - " " - )); - - assertThat(parsedInput).isEqualTo("8"); + public void recognizes8() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", "|_|", "|_|", " "))) + .isEqualTo("8"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes 9") - public void testReaderRecognizesSingle9() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( - " _ ", - "|_|", - " _|", - " " - )); - - assertThat(parsedInput).isEqualTo("9"); + public void recognizes9() { + assertThat(new OpticalCharacterReader().parse(List.of(" _ ", "|_|", " _|", " "))) + .isEqualTo("9"); } @Disabled("Remove to run test") @Test @DisplayName("Recognizes string of decimal numbers") - public void testReaderRecognizesSequence1234567890() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( + public void recognizesStringOfDecimalNumbers() { + assertThat(new OpticalCharacterReader().parse(List.of( " _ _ _ _ _ _ _ _ ", " | _| _||_||_ |_ ||_||_|| |", " ||_ _| | _||_| ||_| _||_|", - " " - )); - - assertThat(parsedInput).isEqualTo("1234567890"); + " "))) + .isEqualTo("1234567890"); } @Disabled("Remove to run test") @Test @DisplayName("Numbers separated by empty lines are recognized. Lines are joined by commas.") - public void testReaderRecognizesAndCorrectlyFormatsMultiRowInput() { - String parsedInput = new OpticalCharacterReader().parse(Arrays.asList( + public void numbersSeparatedByEmptyLinesAreRecognizedLinesAreJoinedByCommas() { + assertThat(new OpticalCharacterReader().parse(List.of( " _ _ ", " | _| _|", " ||_ _|", @@ -254,10 +166,8 @@ public void testReaderRecognizesAndCorrectlyFormatsMultiRowInput() { " _ _ _ ", " ||_||_|", " ||_| _|", - " " - )); - - assertThat(parsedInput).isEqualTo("123,456,789"); + " "))) + .isEqualTo("123,456,789"); } } diff --git a/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java b/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java index 211b4a9b8..63c6edb21 100644 --- a/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java +++ b/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java @@ -1,179 +1,166 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.SortedMap; -import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class PalindromeCalculatorTest { private PalindromeCalculator palindromeCalculator = new PalindromeCalculator(); + private void checkPalindromeWithFactorsMatchesExpected(List> expectedPalindromeFactors, + long expectedValueOfPalindrome, + SortedMap>> actualPalindromes, + long actualValueOfPalindrome) { + assertThat(actualPalindromes).isNotNull(); + assertThat(actualPalindromes.isEmpty()).isFalse(); + + assertThat(actualValueOfPalindrome).isEqualTo(expectedValueOfPalindrome); + + List> actualPalindromeFactors = actualPalindromes.get(actualValueOfPalindrome); + assertThat(actualPalindromeFactors).containsExactlyInAnyOrderElementsOf(expectedPalindromeFactors); + } + @Test @DisplayName("find the smallest palindrome from single digit factors") - public void smallestPalindromeFromSingleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(1, 1) - ) + public void findTheSmallestPalindromeFromSingleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(1, 9); + + List> expected = List.of( + List.of(1, 1) ); long expectedValue = 1L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1, 9); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); } @Disabled("Remove to run test") @Test @DisplayName("find the largest palindrome from single digit factors") - public void largestPalindromeFromSingleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(1, 9), - Arrays.asList(3, 3) - ) + public void findTheLargestPalindromeFromSingleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(1, 9); + + List> expected = List.of( + List.of(1, 9), + List.of(3, 3) ); long expectedValue = 9L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1, 9); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey()); } @Disabled("Remove to run test") @Test @DisplayName("find the smallest palindrome from double digit factors") - public void largestPalindromeFromDoubleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(91, 99) - ) - ); - long expectedValue = 9009L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(10, - 99); + public void findTheSmallestPalindromeFromDoubleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(10, 99); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey()); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("find the largest palindrome from double digit factors") - public void smallestPalindromeFromDoubleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(11, 11) - ) + List> expected = List.of( + List.of(11, 11) ); long expectedValue = 121L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(10, - 99); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); } @Disabled("Remove to run test") @Test - @DisplayName("find the largest palindrome from triple digit factors") - public void largestPalindromeFromTripleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(913, 993) - ) - ); - long expectedValue = 906609L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(100, - 999); + @DisplayName("find the largest palindrome from double digit factors") + public void findTheLargestPalindromeFromDoubleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(10, 99); + List> expected = List.of( + List.of(91, 99) + ); + long expectedValue = 9009L; checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey()); } @Disabled("Remove to run test") @Test @DisplayName("find the smallest palindrome from triple digit factors") - public void smallestPalindromeFromTripleDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(101, 101) - ) + public void findTheSmallestPalindromeFromTripleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(100, 999); + + List> expected = List.of( + List.of(101, 101) ); long expectedValue = 10201L; + checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); + } - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(100, - 999); + @Disabled("Remove to run test") + @Test + @DisplayName("find the largest palindrome from triple digit factors") + public void findTheLargestPalindromeFromTripleDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(100, 999); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); + List> expected = List.of( + List.of(913, 993) + ); + long expectedValue = 906609L; + checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey()); } @Disabled("Remove to run test") @Test @DisplayName("find the smallest palindrome from four digit factors") - public void smallestPalindromeFromQuadDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(1001, 1001) - ) + public void findTheSmallestPalindromeFromFourDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(1000, 9999); + + List> expected = List.of( + List.of(1001, 1001) ); long expectedValue = 1002001L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1000, - 9999); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); } @Disabled("Remove to run test") @Test @DisplayName("find the largest palindrome from four digit factors") - public void largestPalindromeFromQuadDigitFactors() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(9901, 9999) - ) + public void findTheLargestPalindromeFromFourDigitFactors() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(1000, 9999); + + List> expected = List.of( + List.of(9901, 9999) ); long expectedValue = 99000099L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1000, - 9999); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey()); } @Disabled("Remove to run test") @Test @DisplayName("empty result for smallest if no palindrome in the range") - public void emtpyResultSmallestNoPalindromeInRange() { + public void emptyResultForSmallestIfNoPalindromeInTheRange() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(1002, 1003); - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1002, - 1003); - assertThat(palindromes).isEmpty(); + assertThat(palindromes.isEmpty()).isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("empty result for largest if no palindrome in the range") - public void emptyResultLargestNoPalindromeInRange() { + public void emptyResultForLargestIfNoPalindromeInTheRange() { + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(15, 15); - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(15, - 15); - assertThat(palindromes).isEmpty(); + assertThat(palindromes.isEmpty()).isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("error result for smallest if min is more than max") - public void errorSmallestMinIsMoreThanMax() { - + public void errorResultForSmallestIfMinIsMoreThanMax() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> palindromeCalculator.getPalindromeProductsWithFactors(10000, 1)) .withMessage("invalid input: min must be <= max"); @@ -182,8 +169,7 @@ public void errorSmallestMinIsMoreThanMax() { @Disabled("Remove to run test") @Test @DisplayName("error result for largest if min is more than max") - public void errorLargestMinIsMoreThanMax() { - + public void errorResultForLargestIfMinIsMoreThanMax() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> palindromeCalculator.getPalindromeProductsWithFactors(2, 1)) .withMessage("invalid input: min must be <= max"); @@ -193,39 +179,14 @@ public void errorLargestMinIsMoreThanMax() { @Test @DisplayName("smallest product does not use the smallest factor") public void smallestProductDoesNotUseTheSmallestFactor() { - List> expected = Collections.unmodifiableList( - Arrays.asList( - Arrays.asList(3297, 3333) - ) + SortedMap>> palindromes = + palindromeCalculator.getPalindromeProductsWithFactors(3215, 4000); + + List> expected = List.of( + List.of(3297, 3333) ); long expectedValue = 10988901L; - - SortedMap>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(3215, - 4000); - checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey()); } - - private void checkPalindromeWithFactorsMatchesExpected(List> expectedPalindromeFactors, - long expectedValueOfPalindrome, - SortedMap>> actualPalindromes, - long actualValueOfPalindrome) { - assertThat(actualPalindromes) - .isNotNull() - .isNotEmpty(); - - - assertThat(actualValueOfPalindrome).isEqualTo(expectedValueOfPalindrome); - - - List> actualPalindromeFactors = actualPalindromes - .get(actualValueOfPalindrome) - .stream() - .sorted((a, b) -> Integer.compare(a.get(0), b.get(0))) - .collect(Collectors.toList()); - - assertThat(actualPalindromeFactors).containsExactlyElementsOf(expectedPalindromeFactors); - - } } diff --git a/exercises/practice/pangram/src/test/java/PangramCheckerTest.java b/exercises/practice/pangram/src/test/java/PangramCheckerTest.java index 981e40172..30bf3ddc9 100644 --- a/exercises/practice/pangram/src/test/java/PangramCheckerTest.java +++ b/exercises/practice/pangram/src/test/java/PangramCheckerTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,79 +6,83 @@ public class PangramCheckerTest { - private PangramChecker pangramChecker; - - @BeforeEach - public void setup() { - pangramChecker = new PangramChecker(); - } - @Test @DisplayName("empty sentence") - public void emptySentenceIsNotPangram() { - assertThat(pangramChecker.isPangram("")).isFalse(); + public void emptySentence() { + assertThat(new PangramChecker().isPangram("")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("perfect lower case") - public void perfectLowerCasePhraseIsPangram() { - assertThat(pangramChecker.isPangram("abcdefghijklmnopqrstuvwxyz")).isTrue(); + public void perfectLowerCase() { + assertThat(new PangramChecker().isPangram("abcdefghijklmnopqrstuvwxyz")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("only lower case") - public void phraseWithOnlyLowerCaseIsPangram() { - assertThat(pangramChecker.isPangram("the quick brown fox jumps over the lazy dog")).isTrue(); + public void onlyLowerCase() { + assertThat(new PangramChecker().isPangram("the quick brown fox jumps over the lazy dog")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("missing the letter 'x'") - public void phraseMissingCharacterXIsNotPangram() { - assertThat(pangramChecker.isPangram("a quick movement of the enemy will jeopardize five gunboats")).isFalse(); + public void missingTheLetterX() { + assertThat(new PangramChecker().isPangram("a quick movement of the enemy will jeopardize five gunboats")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("missing the letter 'h'") - public void phraseMissingCharacterHIsNotPangram() { - assertThat(pangramChecker.isPangram("five boxing wizards jump quickly at it")).isFalse(); + public void missingTheLetterH() { + assertThat(new PangramChecker().isPangram("five boxing wizards jump quickly at it")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("with underscores") - public void phraseWithUnderscoresIsPangram() { - assertThat(pangramChecker.isPangram("the_quick_brown_fox_jumps_over_the_lazy_dog")).isTrue(); + public void withUnderscores() { + assertThat(new PangramChecker().isPangram("the_quick_brown_fox_jumps_over_the_lazy_dog")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("with numbers") - public void phraseWithNumbersIsPangram() { - assertThat(pangramChecker.isPangram("the 1 quick brown fox jumps over the 2 lazy dogs")).isTrue(); + public void withNumbers() { + assertThat(new PangramChecker().isPangram("the 1 quick brown fox jumps over the 2 lazy dogs")) + .isTrue(); } @Disabled("Remove to run test") @Test @DisplayName("missing letters replaced by numbers") - public void phraseWithMissingLettersReplacedByNumbersIsNotPangram() { - assertThat(pangramChecker.isPangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog")).isFalse(); + public void missingLettersReplacedByNumbers() { + assertThat(new PangramChecker().isPangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog")) + .isFalse(); } @Disabled("Remove to run test") @Test @DisplayName("mixed case and punctuation") - public void phraseWithMixedCaseAndPunctuationIsPangram() { - assertThat(pangramChecker.isPangram("\"Five quacking Zephyrs jolt my wax bed.\"")).isTrue(); + public void mixedCaseAndPunctuation() { + assertThat(new PangramChecker().isPangram("\"Five quacking Zephyrs jolt my wax bed.\"")) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("case insensitive") - public void caseInsensitivePhraseIsNotPangram() { - assertThat(pangramChecker.isPangram("abcdefghijklm ABCDEFGHIJKLM")).isFalse(); + @DisplayName("a-m and A-M are 26 different characters but not a pangram") + public void aMAndAMAre26DifferentCharactersButNotAPangram() { + assertThat(new PangramChecker().isPangram("abcdefghijklm ABCDEFGHIJKLM")) + .isFalse(); } + } diff --git a/exercises/practice/parallel-letter-frequency/src/test/java/ParallelLetterFrequencyTest.java b/exercises/practice/parallel-letter-frequency/src/test/java/ParallelLetterFrequencyTest.java index cce168b52..e568fec95 100644 --- a/exercises/practice/parallel-letter-frequency/src/test/java/ParallelLetterFrequencyTest.java +++ b/exercises/practice/parallel-letter-frequency/src/test/java/ParallelLetterFrequencyTest.java @@ -3,440 +3,434 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class ParallelLetterFrequencyTest { - private String calculateFrequencies = - "There, peeping among the cloud-wrack above a dark tower high up in the mountains," + - "Sam saw a white star twinkle for a while." + - "The beauty of it smote his heart," + - "as he looked up out of the forsaken land," + - "and hope returned to him. For like a shaft," + - "clear and cold, the thought pierced him that in the end," + - "the shadow was only a small and passing thing: there was light and high beauty forever beyond its reach."; - - private String largeTexts1 = - "I am a sick man.... I am a spiteful man. I am an unattractive man.\n" + - "I believe my liver is diseased. However, I know nothing at all about my disease, and do not\n" + - "know for certain what ails me. I don't consult a doctor for it,\n" + - "and never have, though I have a respect for medicine and doctors.\n" + - "Besides, I am extremely superstitious, sufficiently so to respect medicine,\n" + - "anyway (I am well-educated enough not to be superstitious, but I am superstitious).\n" + - "No, I refuse to consult a doctor from spite.\n" + - "That you probably will not understand. Well, I understand it, though.\n" + - "Of course, I can't explain who it is precisely that I am mortifying in this case by my spite:\n" + - "I am perfectly well aware that I cannot \"pay out\" the doctors by not consulting them;\n" + - "I know better than anyone that by all this I am only injuring myself and no one else.\n" + - "But still, if I don't consult a doctor it is from spite.\n" + - "My liver is bad, well - let it get worse!\n" + - "I have been going on like that for a long time - twenty years. Now I am forty.\n" + - "I used to be in the government service, but am no longer.\n" + - "I was a spiteful official. I was rude and took pleasure in being so.\n" + - "I did not take bribes, you see, so I was bound to find a recompense in that, at least.\n" + - "(A poor jest, but I will not scratch it out. I wrote it thinking it would sound very witty;\n" + - "but now that I have seen myself that I only wanted to show off in a despicable way -\n" + - "I will not scratch it out on purpose!) When petitioners used to come for\n" + - "information to the table at which I sat, I used to grind my teeth at them,\n" + - "and felt intense enjoyment when I succeeded in making anybody unhappy.\n" + - "I almost did succeed. For the most part they were all timid people - of course,\n" + - "they were petitioners. But of the uppish ones there was one officer in particular\n" + - "I could not endure. He simply would not be humble, and clanked his sword in a disgusting way.\n" + - "I carried on a feud with him for eighteen months over that sword. At last I got the better of him.\n" + - "He left off clanking it. That happened in my youth, though. But do you know,\n" + - "gentlemen, what was the chief point about my spite? Why, the whole point,\n" + - "the real sting of it lay in the fact that continually, even in the moment of the acutest spleen,\n" + - "I was inwardly conscious with shame that I was not only not a spiteful but not even an embittered man,\n" + - "that I was simply scaring sparrows at random and amusing myself by it.\n" + - "I might foam at the mouth, but bring me a doll to play with, give me a cup of tea with sugar in it,\n" + - "and maybe I should be appeased. I might even be genuinely touched,\n" + - "though probably I should grind my teeth at myself afterwards and lie awake at night with shame for\n" + - "months after. That was my way. I was lying when I said just now that I was a spiteful official.\n" + - "I was lying from spite. I was simply amusing myself with the petitioners and with the officer,\n" + - "and in reality I never could become spiteful. I was conscious every moment in myself of many,\n" + - "very many elements absolutely opposite to that. I felt them positively swarming in me,\n" + - "these opposite elements." + - "I knew that they had been swarming in me all my life and craving some outlet from me,\n" + - "but I would not let them, would not let them, purposely would not let them come out.\n" + - "They tormented me till I was ashamed: they drove me to convulsions and - sickened me, at last,\n" + - "how they sickened me!"; - - private String largeTexts2 = - "Gentlemen, I am joking, and I know myself that my jokes are not brilliant\n" + - ",but you know one can take everything as a joke." + - "I am, perhaps, jesting against the grain.\n" + - "Gentlemen, I am tormented by questions; answer them for me." + - "You, for instance, want to cure men of their\n" + - "old habits and reform their will in accordance with science and good sense.\n" + - "But how do you know, not only that it is possible, but also that it is\n" + - "desirable to reform man in that way?" + - "And what leads you to the conclusion that man's\n" + - "inclinations need reforming? In short," + - "how do you know that such a reformation will be a benefit to man?\n" + - "And to go to the root of the matter, why are you so positively convinced that not to act against\n" + - "his real normal interests guaranteed by the conclusions of reason and arithmetic is certainly always\n" + - "advantageous for man and must always be a law for mankind? So far, you know,\n" + - "this is only your supposition." + - "It may be the law of logic, but not the law of humanity.\n" + - "You think, gentlemen, perhaps that I am mad? Allow me to defend myself. I agree that man\n" + - "is pre-eminently a creative animal," + - "predestined to strive consciously for an object and to engage in engineering -\n" + - "that is, incessantly and eternally to make new roads, wherever\n" + - "they may lead. But the reason why he wants sometimes to go off at a tangent may just be that he is\n" + - "predestined to make the road, and perhaps, too, that however stupid the \"direct\"\n" + - "practical man may be, the thought sometimes will occur to him that the road almost always does lead\n" + - "somewhere, and that the destination it leads to is less important than the process\n" + - "of making it, and that the chief thing is to save the well-conducted child from despising engineering,\n" + - "and so giving way to the fatal idleness, which, as we all know,\n" + - "is the mother of all the vices. Man likes to make roads and to create, that is a fact beyond dispute.\n" + - "But why has he such a passionate love for destruction and chaos also?\n" + - "Tell me that! But on that point I want to say a couple of words myself." + - "May it not be that he loves\n" + - "chaos and destruction (there can be no disputing that he does sometimes love it)\n" + - "because he is instinctively afraid of attaining his object and completing the edifice he is constructing?\n" + - "Who knows, perhaps he only loves that edifice from a distance, and is by no means\n" + - "in love with it at close quarters; perhaps he only loves building it and does not want to live in it,\n" + - "but will leave it, when completed, for the use of les animaux domestiques -\n" + - "such as the ants, the sheep, and so on. Now the ants have quite a different taste.\n" + - "They have a marvellous edifice of that pattern which endures for ever - the ant-heap.\n" + - "With the ant-heap the respectable race of ants began and with the ant-heap they will probably end,\n" + - "which does the greatest credit to their perseverance and good sense. But man is a frivolous and\n" + - "incongruous creature, and perhaps, like a chess player, loves the process of the game, not the end of it.\n" + - "And who knows (there is no saying with certainty), perhaps the only goal on earth\n" + - "to which mankind is striving lies in this incessant process of attaining, in other words,\n" + - "in life itself, and not in the thing to be attained, which must always be expressed as a formula,\n" + - "as positive as twice two makes four, and such positiveness is not life, gentlemen,\n" + - "but is the beginning of death."; - - private String largeTexts3 = - "But these are all golden dreams. Oh, tell me, who was it first announced,\n" + - "who was it first proclaimed," + - "that man only does nasty things because he does not know his own interests;\n" + - "and that if he were enlightened, if his eyes were opened to his real normal interests,\n" + - "man would at once cease to do nasty things, would at once become good and noble because,\n" + - "being enlightened and understanding his real advantage, he would see his own advantage in the\n" + - "good and nothing else, and we all know that not one man can, consciously, act against his own interests,\n" + - "consequently, so to say, through necessity, he would begin doing good? Oh, the babe! Oh, the pure,\n" + - "innocent child! Why, in the first place, when in all these thousands of years has there been a time\n" + - "when man has acted only from his own interest? What is to be done with the millions of facts that bear\n" + - "witness that men, consciously, that is fully understanding their real interests, have left them in the\n" + - "background and have rushed headlong on another path, to meet peril and danger,\n" + - "compelled to this course by nobody and by nothing, but, as it were, simply disliking the beaten track,\n" + - "and have obstinately, wilfully, struck out another difficult, absurd way," + - "seeking it almost in the darkness.\n" + - "So, I suppose, this obstinacy and perversity were pleasanter to them than any advantage....\n" + - "Advantage! What is advantage?" + - "And will you take it upon yourself to define with perfect accuracy in what the\n" + - "advantage of man consists? And what if it so happens that a man's advantage, sometimes, not only may,\n" + - "but even must, consist in his desiring in certain cases what is harmful to himself and not advantageous.\n" + - "And if so, if there can be such a case, the whole principle falls into dust. What do you think -\n" + - "are there such cases? You laugh; laugh away, gentlemen, but only answer me: have man's advantages been\n" + - "reckoned up with perfect certainty? Are there not some which not only have not been included but cannot\n" + - "possibly be included under any classification? You see, you gentlemen have, to the best of my knowledge,\n" + - "taken your whole register of human advantages from the averages of statistical figures and\n" + - "politico-economical formulas." + - "Your advantages are prosperity, wealth, freedom, peace - and so on, and so on.\n" + - "So that the man who should, for instance," + - "go openly and knowingly in opposition to all that list would to your thinking,\n" + - "and indeed mine, too, of course, be an obscurantist or an absolute madman: would not he?" + - "But, you know, this is\n" + - "what is surprising: why does it so happen that all these statisticians," + - "sages and lovers of humanity,\n" + - "when they reckon up human advantages invariably leave out one?" + - "They don't even take it into their reckoning\n" + - "in the form in which it should be taken, and the whole reckoning depends upon that." + - "It would be no greater matter,\n" + - "they would simply have to take it, this advantage, and add it to the list." + - "But the trouble is, that this strange\n" + - "advantage does not fall under any classification and is not in place in any list." + - "I have a friend for instance ...\n" + - "Ech! gentlemen, but of course he is your friend, too; and indeed there is no one," + - "no one to whom he is not a friend!"; - - private String largeTexts4 = - "Yes, but here I come to a stop! Gentlemen, you must excuse me for being over-philosophical;\n" + - "it's the result of forty years underground! Allow me to indulge my fancy." + - "You see, gentlemen, reason is an excellent thing,\n" + - "there's no disputing that," + - "but reason is nothing but reason and satisfies only the rational side of man's nature,\n" + - "while will is a manifestation of the whole life, that is," + - "of the whole human life including reason and all the impulses.\n" + - "And although our life, in this manifestation of it, is often worthless," + - "yet it is life and not simply extracting square roots.\n" + - "Here I, for instance, quite naturally want to live, in order to satisfy all my capacities for life," + - "and not simply my capacity\n" + - "for reasoning, that is, not simply one twentieth of my capacity for life. What does reason know?" + - "Reason only knows what it has\n" + - "succeeded in learning (some things, perhaps, it will never learn;" + - "this is a poor comfort, but why not say so frankly?)\n" + - "and human nature acts as a whole, with everything that is in it," + - "consciously or unconsciously, and, even it if goes wrong, it lives.\n" + - "I suspect, gentlemen, that you are looking at me with compassion;" + - "you tell me again that an enlightened and developed man,\n" + - "such, in short, as the future man will be, cannot consciously desire anything disadvantageous to himself," + - "that that can be proved mathematically.\n" + - "I thoroughly agree, it can - by mathematics." + - "But I repeat for the hundredth time, there is one case, one only, when man may consciously, purposely,\n" + - "desire what is injurious to himself, what is stupid," + - "very stupid - simply in order to have the right to desire for himself even what is very stupid\n" + - "and not to be bound by an obligation to desire only what is sensible." + - "Of course, this very stupid thing, this caprice of ours, may be in reality,\n" + - "gentlemen, more advantageous for us than anything else on earth, especially in certain cases." + - "And in particular it may be more advantageous than\n" + - "any advantage even when it does us obvious harm," + - "and contradicts the soundest conclusions of our reason concerning our advantage -\n" + - "for in any circumstances it preserves for us what is most precious and most important - that is," + - "our personality, our individuality.\n" + - "Some, you see, maintain that this really is the most precious thing for mankind;" + - "choice can, of course, if it chooses, be in agreement\n" + - "with reason; and especially if this be not abused but kept within bounds." + - "It is profitable and some- times even praiseworthy.\n" + - "But very often, and even most often," + - "choice is utterly and stubbornly opposed to reason ... and ... and ... do you know that that,\n" + - "too, is profitable, sometimes even praiseworthy? Gentlemen, let us suppose that man is not stupid." + - "(Indeed one cannot refuse to suppose that,\n" + - "if only from the one consideration, that, if man is stupid, then who is wise?)" + - "But if he is not stupid, he is monstrously ungrateful!\n" + - "Phenomenally ungrateful. In fact, I believe that the best definition of man is the ungrateful biped." + - "But that is not all, that is not his worst defect;\n" + - "his worst defect is his perpetual moral obliquity, perpetual" + - "- from the days of the Flood to the Schleswig-Holstein period."; + private static String[] createIdenticalTexts(int count, String text) { + String[] arr = new String[count]; + Arrays.fill(arr, text); + return arr; + } @Test @DisplayName("no texts") - public void testNoTexts() { - String[] input = {}; - Map expectedOutput = new HashMap<>(); + public void noTexts() { + String[] input = new String[]{}; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of()); } @Disabled("Remove to run test") @Test @DisplayName("one text with one letter") - public void testOneTextWithOneLetter() { - String[] input = { "a" }; - Map expectedOutput = new HashMap<>() { - { - put('a', 1); - } + public void oneTextWithOneLetter() { + String[] input = new String[]{ + "a" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('a', 1)); } @Disabled("Remove to run test") @Test @DisplayName("one text with multiple letters") - public void testOneTextWithMultipleLetters() { - String[] input = { "bbcccd" }; - Map expectedOutput = new HashMap<>() { - { - put('b', 2); - put('c', 3); - put('d', 1); - } + public void oneTextWithMultipleLetters() { + String[] input = new String[]{ + "bbcccd" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('b', 2, 'c', 3, 'd', 1)); } @Disabled("Remove to run test") @Test @DisplayName("two texts with one letter") - public void testTwoTextsWithOneLetter() { - String[] input = { "e", "f" }; - Map expectedOutput = new HashMap<>() { - { - put('e', 1); - put('f', 1); - } + public void twoTextsWithOneLetter() { + String[] input = new String[]{ + "e", + "f" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('e', 1, 'f', 1)); } @Disabled("Remove to run test") @Test @DisplayName("two texts with multiple letters") - public void testTwoTextsWithMultipleLetters() { - String[] input = { "ggh", "hhi" }; - Map expectedOutput = new HashMap<>() { - { - put('g', 2); - put('h', 3); - put('i', 1); - } + public void twoTextsWithMultipleLetters() { + String[] input = new String[]{ + "ggh", + "hhi" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('g', 2, 'h', 3, 'i', 1)); } @Disabled("Remove to run test") @Test @DisplayName("ignore letter casing") - public void testIgnoreLetterCasing() { - String[] input = { "m", "M" }; - Map expectedOutput = new HashMap<>() { - { - put('m', 2); - } + public void ignoreLetterCasing() { + String[] input = new String[]{ + "m", + "M" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('m', 2)); } @Disabled("Remove to run test") @Test @DisplayName("ignore whitespace") - public void testIgnoreWhitespace() { - String[] input = { " ", "\t", "\r\n" }; - Map expectedOutput = new HashMap<>(); + public void ignoreWhitespace() { + String[] input = new String[]{ + " ", + "\t", + "\r\n" + }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of()); } @Disabled("Remove to run test") @Test @DisplayName("ignore punctuation") - public void testIgnorePunctuation() { - String[] input = { "!", "?", ";", ",", "." }; - Map expectedOutput = new HashMap<>(); + public void ignorePunctuation() { + String[] input = new String[]{ + "!", + "?", + ";", + ",", + "." + }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of()); } @Disabled("Remove to run test") @Test @DisplayName("ignore numbers") - public void testIgnoreNumbers() { - String[] input = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; - Map expectedOutput = new HashMap<>(); + public void ignoreNumbers() { + String[] input = new String[]{ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of()); } @Disabled("Remove to run test") @Test @DisplayName("Unicode letters") - public void testUnicodeLetters() { - String[] input = { "本", "φ", "ほ", "ø" }; - Map expectedOutput = new HashMap<>() { - { - put('本', 1); - put('φ', 1); - put('ほ', 1); - put('ø', 1); - } + public void unicodeLetters() { + String[] input = new String[]{ + "本", + "φ", + "ほ", + "ø" }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('本', 1, 'φ', 1, 'ほ', 1, 'ø', 1)); } @Disabled("Remove to run test") @Test @DisplayName("combination of lower- and uppercase letters, punctuation and white space") - public void testCombinationOfLowerAndUppercaseLettersPunctuationAndWhiteSpace() { - String[] input = {calculateFrequencies}; - Map expectedOutput = new HashMap<>() { - { - put('a', 32); - put('b', 4); - put('c', 6); - put('d', 14); - put('e', 37); - put('f', 7); - put('g', 8); - put('h', 29); - put('i', 19); - put('k', 6); - put('l', 12); - put('m', 7); - put('n', 19); - put('o', 22); - put('p', 7); - put('r', 17); - put('s', 16); - put('t', 30); - put('u', 9); - put('v', 2); - put('w', 9); - put('y', 4); - } + public void combinationOfLowerAndUppercaseLettersPunctuationAndWhiteSpace() { + String[] input = new String[]{ + "There, peeping among the cloud-wrack above a dark tower high up in the " + + "mountains, Sam saw a white star twinkle for a while. The beauty of it " + + "smote his heart, as he looked up out of the forsaken land, and hope " + + "returned to him. For like a shaft, clear and cold, the thought pierced " + + "him that in the end, the shadow was only a small and passing thing: " + + "there was light and high beauty forever beyond its reach." }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.ofEntries( + Map.entry('a', 32), + Map.entry('b', 4), + Map.entry('c', 6), + Map.entry('d', 14), + Map.entry('e', 37), + Map.entry('f', 7), + Map.entry('g', 8), + Map.entry('h', 29), + Map.entry('i', 19), + Map.entry('k', 6), + Map.entry('l', 12), + Map.entry('m', 7), + Map.entry('n', 19), + Map.entry('o', 22), + Map.entry('p', 7), + Map.entry('r', 17), + Map.entry('s', 16), + Map.entry('t', 30), + Map.entry('u', 9), + Map.entry('v', 2), + Map.entry('w', 9), + Map.entry('y', 4) + )); } @Disabled("Remove to run test") @Test @DisplayName("large texts") - public void testLargeTexts() { - String[] input = { largeTexts1, largeTexts2, largeTexts3, largeTexts4 }; - Map expectedOutput = new HashMap<>() { - { - put('a', 845); - put('b', 155); - put('c', 278); - put('d', 359); - put('e', 1143); - put('f', 222); - put('g', 187); - put('h', 507); - put('i', 791); - put('j', 12); - put('k', 67); - put('l', 423); - put('m', 288); - put('n', 833); - put('o', 791); - put('p', 197); - put('q', 8); - put('r', 432); - put('s', 700); - put('t', 1043); - put('u', 325); - put('v', 111); - put('w', 223); - put('x', 7); - put('y', 251); - } + public void largeTexts() { + String[] input = new String[]{ + "I am a sick man.... I am a spiteful man. I am an unattractive man.\nI " + + "believe my liver is diseased. However, I know nothing at all about my " + + "disease, and do not\nknow for certain what ails me. I don't consult a " + + "doctor for it,\nand never have, though I have a respect for medicine " + + "and doctors.\nBesides, I am extremely superstitious, sufficiently so to " + + "respect medicine,\nanyway (I am well-educated enough not to be " + + "superstitious, but I am superstitious).\nNo, I refuse to consult a " + + "doctor from spite.\nThat you probably will not understand. Well, I " + + "understand it, though.\nOf course, I can't explain who it is precisely " + + "that I am mortifying in this case by my spite:\nI am perfectly well " + + "aware that I cannot \"pay out\" the doctors by not consulting them;\nI " + + "know better than anyone that by all this I am only injuring myself and " + + "no one else.\nBut still, if I don't consult a doctor it is from " + + "spite.\nMy liver is bad, well - let it get worse!\nI have been going on " + + "like that for a long time - twenty years. Now I am forty.\nI used to be " + + "in the government service, but am no longer.\nI was a spiteful " + + "official. I was rude and took pleasure in being so.\nI did not take " + + "bribes, you see, so I was bound to find a recompense in that, at " + + "least.\n(A poor jest, but I will not scratch it out. I wrote it " + + "thinking it would sound very witty;\nbut now that I have seen myself " + + "that I only wanted to show off in a despicable way -\nI will not " + + "scratch it out on purpose!) When petitioners used to come " + + "for\ninformation to the table at which I sat, I used to grind my teeth " + + "at them,\nand felt intense enjoyment when I succeeded in making anybody " + + "unhappy.\nI almost did succeed. For the most part they were all timid " + + "people - of course,\nthey were petitioners. But of the uppish ones " + + "there was one officer in particular\nI could not endure. He simply " + + "would not be humble, and clanked his sword in a disgusting way.\nI " + + "carried on a feud with him for eighteen months over that sword. At " + + "last I got the better of him.\nHe left off clanking it. That happened " + + "in my youth, though. But do you know,\ngentlemen, what was the chief " + + "point about my spite? Why, the whole point,\nthe real sting of it lay " + + "in the fact that continually, even in the moment of the acutest " + + "spleen,\nI was inwardly conscious with shame that I was not only not a " + + "spiteful but not even an embittered man,\nthat I was simply scaring " + + "sparrows at random and amusing myself by it.\nI might foam at the " + + "mouth, but bring me a doll to play with, give me a cup of tea with " + + "sugar in it,\nand maybe I should be appeased. I might even be genuinely " + + "touched,\nthough probably I should grind my teeth at myself afterwards " + + "and lie awake at night with shame for\nmonths after. That was my way. I " + + "was lying when I said just now that I was a spiteful official.\nI was " + + "lying from spite. I was simply amusing myself with the petitioners and " + + "with the officer,\nand in reality I never could become spiteful. I was " + + "conscious every moment in myself of many,\nvery many elements " + + "absolutely opposite to that. I felt them positively swarming in " + + "me,\nthese opposite elements. I knew that they had been swarming in me " + + "all my life and craving some outlet from me,\nbut I would not let them, " + + "would not let them, purposely would not let them come out.\nThey " + + "tormented me till I was ashamed: they drove me to convulsions and - " + + "sickened me, at last,\nhow they sickened me!", + "Gentlemen, I am joking, and I know myself that my jokes are not " + + "brilliant\n,but you know one can take everything as a joke. I am, " + + "perhaps, jesting against the grain.\nGentlemen, I am tormented by " + + "questions; answer them for me. You, for instance, want to cure men of " + + "their\nold habits and reform their will in accordance with science and " + + "good sense.\nBut how do you know, not only that it is possible, but " + + "also that it is\ndesirable to reform man in that way? And what leads " + + "you to the conclusion that man's\ninclinations need reforming? In " + + "short, how do you know that such a reformation will be a benefit to " + + "man?\nAnd to go to the root of the matter, why are you so positively " + + "convinced that not to act against\nhis real normal interests guaranteed " + + "by the conclusions of reason and arithmetic is certainly " + + "always\nadvantageous for man and must always be a law for mankind? So " + + "far, you know,\nthis is only your supposition. It may be the law of " + + "logic, but not the law of humanity.\nYou think, gentlemen, perhaps that " + + "I am mad? Allow me to defend myself. I agree that man\nis pre-eminently " + + "a creative animal, predestined to strive consciously for an object and " + + "to engage in engineering -\nthat is, incessantly and eternally to make " + + "new roads, wherever\nthey may lead. But the reason why he wants " + + "sometimes to go off at a tangent may just be that he is\npredestined to " + + "make the road, and perhaps, too, that however stupid the " + + "\"direct\"\npractical man may be, the thought sometimes will occur to him " + + "that the road almost always does lead\nsomewhere, and that the " + + "destination it leads to is less important than the process\nof making " + + "it, and that the chief thing is to save the well-conducted child from " + + "despising engineering,\nand so giving way to the fatal idleness, which, " + + "as we all know,\nis the mother of all the vices. Man likes to make " + + "roads and to create, that is a fact beyond dispute.\nBut why has he " + + "such a passionate love for destruction and chaos also?\nTell me that! " + + "But on that point I want to say a couple of words myself. May it not " + + "be that he loves\nchaos and destruction (there can be no disputing that " + + "he does sometimes love it)\nbecause he is instinctively afraid of " + + "attaining his object and completing the edifice he is " + + "constructing?\nWho knows, perhaps he only loves that edifice from a " + + "distance, and is by no means\nin love with it at close quarters; " + + "perhaps he only loves building it and does not want to live in it,\nbut " + + "will leave it, when completed, for the use of les animaux domestiques " + + "-\nsuch as the ants, the sheep, and so on. Now the ants have quite a " + + "different taste.\nThey have a marvellous edifice of that pattern which " + + "endures for ever - the ant-heap.\nWith the ant-heap the respectable " + + "race of ants began and with the ant-heap they will probably end,\nwhich " + + "does the greatest credit to their perseverance and good sense. But man " + + "is a frivolous and\nincongruous creature, and perhaps, like a chess " + + "player, loves the process of the game, not the end of it.\nAnd who " + + "knows (there is no saying with certainty), perhaps the only goal on " + + "earth\nto which mankind is striving lies in this incessant process of " + + "attaining, in other words,\nin life itself, and not in the thing to be " + + "attained, which must always be expressed as a formula,\nas positive as " + + "twice two makes four, and such positiveness is not life, " + + "gentlemen,\nbut is the beginning of death.", + "But these are all golden dreams. Oh, tell me, who was it first " + + "announced,\nwho was it first proclaimed, that man only does nasty " + + "things because he does not know his own interests;\nand that if he were " + + "enlightened, if his eyes were opened to his real normal interests,\nman " + + "would at once cease to do nasty things, would at once become good and " + + "noble because,\nbeing enlightened and understanding his real advantage, " + + "he would see his own advantage in the\ngood and nothing else, and we " + + "all know that not one man can, consciously, act against his own " + + "interests,\nconsequently, so to say, through necessity, he would begin " + + "doing good? Oh, the babe! Oh, the pure,\ninnocent child! Why, in the " + + "first place, when in all these thousands of years has there been a " + + "time\nwhen man has acted only from his own interest? What is to be done " + + "with the millions of facts that bear\nwitness that men, consciously, " + + "that is fully understanding their real interests, have left them in " + + "the\nbackground and have rushed headlong on another path, to meet peril " + + "and danger,\ncompelled to this course by nobody and by nothing, but, as " + + "it were, simply disliking the beaten track,\nand have obstinately, " + + "wilfully, struck out another difficult, absurd way, seeking it almost " + + "in the darkness.\nSo, I suppose, this obstinacy and perversity were " + + "pleasanter to them than any advantage....\nAdvantage! What is " + + "advantage? And will you take it upon yourself to define with perfect " + + "accuracy in what the\nadvantage of man consists? And what if it so " + + "happens that a man's advantage, sometimes, not only may,\nbut even " + + "must, consist in his desiring in certain cases what is harmful to " + + "himself and not advantageous.\nAnd if so, if there can be such a case, " + + "the whole principle falls into dust. What do you think -\nare there " + + "such cases? You laugh; laugh away, gentlemen, but only answer me: have " + + "man's advantages been\nreckoned up with perfect certainty? Are there " + + "not some which not only have not been included but cannot\npossibly be " + + "included under any classification? You see, you gentlemen have, to the " + + "best of my knowledge,\ntaken your whole register of human advantages " + + "from the averages of statistical figures and\npolitico-economical " + + "formulas. Your advantages are prosperity, wealth, freedom, peace - and " + + "so on, and so on.\nSo that the man who should, for instance, go openly " + + "and knowingly in opposition to all that list would to your " + + "thinking,\nand indeed mine, too, of course, be an obscurantist or an " + + "absolute madman: would not he? But, you know, this is\nwhat is " + + "surprising: why does it so happen that all these statisticians, sages " + + "and lovers of humanity,\nwhen they reckon up human advantages " + + "invariably leave out one? They don't even take it into their " + + "reckoning\nin the form in which it should be taken, and the whole " + + "reckoning depends upon that. It would be no greater matter,\nthey would " + + "simply have to take it, this advantage, and add it to the list. But " + + "the trouble is, that this strange\nadvantage does not fall under any " + + "classification and is not in place in any list. I have a friend for " + + "instance ...\nEch! gentlemen, but of course he is your friend, too; and " + + "indeed there is no one, no one to whom he is not a friend!", + "Yes, but here I come to a stop! Gentlemen, you must excuse me for " + + "being over-philosophical;\nit's the result of forty years underground! " + + "Allow me to indulge my fancy. You see, gentlemen, reason is an " + + "excellent thing,\nthere's no disputing that, but reason is nothing but " + + "reason and satisfies only the rational side of man's nature,\nwhile " + + "will is a manifestation of the whole life, that is, of the whole human " + + "life including reason and all the impulses.\nAnd although our life, in " + + "this manifestation of it, is often worthless, yet it is life and not " + + "simply extracting square roots.\nHere I, for instance, quite naturally " + + "want to live, in order to satisfy all my capacities for life, and not " + + "simply my capacity\nfor reasoning, that is, not simply one twentieth of " + + "my capacity for life. What does reason know? Reason only knows what it " + + "has\nsucceeded in learning (some things, perhaps, it will never learn; " + + "this is a poor comfort, but why not say so frankly?)\nand human nature " + + "acts as a whole, with everything that is in it, consciously or " + + "unconsciously, and, even it if goes wrong, it lives.\nI suspect, " + + "gentlemen, that you are looking at me with compassion; you tell me " + + "again that an enlightened and developed man,\nsuch, in short, as the " + + "future man will be, cannot consciously desire anything disadvantageous " + + "to himself, that that can be proved mathematically.\nI thoroughly " + + "agree, it can - by mathematics. But I repeat for the hundredth time, " + + "there is one case, one only, when man may consciously, " + + "purposely,\ndesire what is injurious to himself, what is stupid, very " + + "stupid - simply in order to have the right to desire for himself even " + + "what is very stupid\nand not to be bound by an obligation to desire " + + "only what is sensible. Of course, this very stupid thing, this caprice " + + "of ours, may be in reality,\ngentlemen, more advantageous for us than " + + "anything else on earth, especially in certain cases. And in particular " + + "it may be more advantageous than\nany advantage even when it does us " + + "obvious harm, and contradicts the soundest conclusions of our reason " + + "concerning our advantage -\nfor in any circumstances it preserves for " + + "us what is most precious and most important - that is, our " + + "personality, our individuality.\nSome, you see, maintain that this " + + "really is the most precious thing for mankind; choice can, of course, " + + "if it chooses, be in agreement\nwith reason; and especially if this be " + + "not abused but kept within bounds. It is profitable and some- times " + + "even praiseworthy.\nBut very often, and even most often, choice is " + + "utterly and stubbornly opposed to reason ... and ... and ... do you " + + "know that that,\ntoo, is profitable, sometimes even praiseworthy? " + + "Gentlemen, let us suppose that man is not stupid. (Indeed one cannot " + + "refuse to suppose that,\nif only from the one consideration, that, if " + + "man is stupid, then who is wise?) But if he is not stupid, he is " + + "monstrously ungrateful!\nPhenomenally ungrateful. In fact, I believe " + + "that the best definition of man is the ungrateful biped. But that is " + + "not all, that is not his worst defect;\nhis worst defect is his " + + "perpetual moral obliquity, perpetual - from the days of the Flood to " + + "the Schleswig-Holstein period." }; ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.ofEntries( + Map.entry('a', 845), + Map.entry('b', 155), + Map.entry('c', 278), + Map.entry('d', 359), + Map.entry('e', 1143), + Map.entry('f', 222), + Map.entry('g', 187), + Map.entry('h', 507), + Map.entry('i', 791), + Map.entry('j', 12), + Map.entry('k', 67), + Map.entry('l', 423), + Map.entry('m', 288), + Map.entry('n', 833), + Map.entry('o', 791), + Map.entry('p', 197), + Map.entry('q', 8), + Map.entry('r', 432), + Map.entry('s', 700), + Map.entry('t', 1043), + Map.entry('u', 325), + Map.entry('v', 111), + Map.entry('w', 223), + Map.entry('x', 7), + Map.entry('y', 251) + )); } @Disabled("Remove to run test") @Test @DisplayName("many small texts") - public void testManySmallTexts() { - String[] input = new String[50]; - Arrays.fill(input, "abbccc"); - Map expectedOutput = new HashMap<>() { - { - put('a', 50); - put('b', 100); - put('c', 150); - } - }; + public void manySmallTexts() { + String[] input = createIdenticalTexts(50, "abbccc"); ParallelLetterFrequency p = new ParallelLetterFrequency(input); - assertThat(p.countLetters()).isEqualTo(expectedOutput); + assertThat(p.countLetters()).isEqualTo(Map.of('a', 50, 'b', 100, 'c', 150)); } } diff --git a/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java b/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java index becdb0825..4de7be51e 100644 --- a/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java +++ b/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java @@ -6,115 +6,98 @@ public class PascalsTriangleGeneratorTest { - private PascalsTriangleGenerator pascalsTriangleGenerator = - new PascalsTriangleGenerator(); + private PascalsTriangleGenerator pascalsTriangleGenerator = new PascalsTriangleGenerator(); @Test @DisplayName("zero rows") - public void testTriangleWithZeroRows() { - int[][] expectedOutput = new int[][]{}; - - assertThat(pascalsTriangleGenerator.generateTriangle(0)).isEqualTo(expectedOutput); + public void zeroRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(0)) + .isDeepEqualTo(new int[][]{}); } @Disabled("Remove to run test") @Test @DisplayName("single row") - public void testTriangleWithOneRow() { - int[][] expectedOutput = new int[][]{ - {1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(1)).isEqualTo(expectedOutput); + public void singleRow() { + assertThat(pascalsTriangleGenerator.generateTriangle(1)) + .isDeepEqualTo(new int[][]{{1}}); } @Disabled("Remove to run test") @Test @DisplayName("two rows") - public void testTriangleWithTwoRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(2)).isEqualTo(expectedOutput); + public void twoRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(2)) + .isDeepEqualTo(new int[][]{{1}, {1, 1}}); } @Disabled("Remove to run test") @Test @DisplayName("three rows") - public void testTriangleWithThreeRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1}, - {1, 2, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(3)).isEqualTo(expectedOutput); + public void threeRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(3)) + .isDeepEqualTo(new int[][]{{1}, {1, 1}, {1, 2, 1}}); } @Disabled("Remove to run test") @Test @DisplayName("four rows") - public void testTriangleWithFourRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1}, - {1, 2, 1}, - {1, 3, 3, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(4)).isEqualTo(expectedOutput); + public void fourRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(4)) + .isDeepEqualTo(new int[][]{ + {1}, + {1, 1}, + {1, 2, 1}, + {1, 3, 3, 1} + }); } @Disabled("Remove to run test") @Test @DisplayName("five rows") - public void testTriangleWithFiveRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1}, - {1, 2, 1}, - {1, 3, 3, 1}, - {1, 4, 6, 4, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(5)).isEqualTo(expectedOutput); + public void fiveRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(5)) + .isDeepEqualTo(new int[][]{ + {1}, + {1, 1}, + {1, 2, 1}, + {1, 3, 3, 1}, + {1, 4, 6, 4, 1} + }); } @Disabled("Remove to run test") @Test @DisplayName("six rows") - public void testTriangleWithSixRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1}, - {1, 2, 1}, - {1, 3, 3, 1}, - {1, 4, 6, 4, 1}, - {1, 5, 10, 10, 5, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(6)).isEqualTo(expectedOutput); + public void sixRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(6)) + .isDeepEqualTo(new int[][]{ + {1}, + {1, 1}, + {1, 2, 1}, + {1, 3, 3, 1}, + {1, 4, 6, 4, 1}, + {1, 5, 10, 10, 5, 1} + }); } @Disabled("Remove to run test") @Test @DisplayName("ten rows") - public void testTriangleWithTenRows() { - int[][] expectedOutput = new int[][]{ - {1}, - {1, 1}, - {1, 2, 1}, - {1, 3, 3, 1}, - {1, 4, 6, 4, 1}, - {1, 5, 10, 10, 5, 1}, - {1, 6, 15, 20, 15, 6, 1}, - {1, 7, 21, 35, 35, 21, 7, 1}, - {1, 8, 28, 56, 70, 56, 28, 8, 1}, - {1, 9, 36, 84, 126, 126, 84, 36, 9, 1} - }; - - assertThat(pascalsTriangleGenerator.generateTriangle(10)).isEqualTo(expectedOutput); + public void tenRows() { + assertThat(pascalsTriangleGenerator.generateTriangle(10)) + .isDeepEqualTo(new int[][]{ + {1}, + {1, 1}, + {1, 2, 1}, + {1, 3, 3, 1}, + {1, 4, 6, 4, 1}, + {1, 5, 10, 10, 5, 1}, + {1, 6, 15, 20, 15, 6, 1}, + {1, 7, 21, 35, 35, 21, 7, 1}, + {1, 8, 28, 56, 70, 56, 28, 8, 1}, + {1, 9, 36, 84, 126, 126, 84, 36, 9, 1} + }); } + } diff --git a/exercises/practice/perfect-numbers/src/test/java/NaturalNumberTest.java b/exercises/practice/perfect-numbers/src/test/java/NaturalNumberTest.java index fb2f3600d..b1457f017 100644 --- a/exercises/practice/perfect-numbers/src/test/java/NaturalNumberTest.java +++ b/exercises/practice/perfect-numbers/src/test/java/NaturalNumberTest.java @@ -8,108 +8,108 @@ public class NaturalNumberTest { @Test - @DisplayName("Smallest perfect number is classified correctly") - public void testSmallPerfectNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(6).getClassification()).isEqualTo(Classification.PERFECT); + @DisplayName("Perfect numbers -> Smallest perfect number is classified correctly") + public void perfectNumbersSmallestPerfectNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(6).getClassification()) + .isEqualTo(Classification.PERFECT); } @Disabled("Remove to run test") @Test - @DisplayName("Medium perfect number is classified correctly") - public void testMediumPerfectNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(28).getClassification()).isEqualTo(Classification.PERFECT); + @DisplayName("Perfect numbers -> Medium perfect number is classified correctly") + public void perfectNumbersMediumPerfectNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(28).getClassification()) + .isEqualTo(Classification.PERFECT); } @Disabled("Remove to run test") @Test - @DisplayName("Large perfect number is classified correctly") - public void testLargePerfectNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(33550336).getClassification()).isEqualTo(Classification.PERFECT); + @DisplayName("Perfect numbers -> Large perfect number is classified correctly") + public void perfectNumbersLargePerfectNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(33550336).getClassification()) + .isEqualTo(Classification.PERFECT); } @Disabled("Remove to run test") @Test - @DisplayName("Smallest abundant number is classified correctly") - public void testSmallAbundantNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(12).getClassification()).isEqualTo(Classification.ABUNDANT); + @DisplayName("Abundant numbers -> Smallest abundant number is classified correctly") + public void abundantNumbersSmallestAbundantNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(12).getClassification()) + .isEqualTo(Classification.ABUNDANT); } @Disabled("Remove to run test") @Test - @DisplayName("Medium abundant number is classified correctly") - public void testMediumAbundantNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(30).getClassification()).isEqualTo(Classification.ABUNDANT); + @DisplayName("Abundant numbers -> Medium abundant number is classified correctly") + public void abundantNumbersMediumAbundantNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(30).getClassification()) + .isEqualTo(Classification.ABUNDANT); } @Disabled("Remove to run test") @Test - @DisplayName("Large abundant number is classified correctly") - public void testLargeAbundantNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(33550335).getClassification()).isEqualTo(Classification.ABUNDANT); + @DisplayName("Abundant numbers -> Large abundant number is classified correctly") + public void abundantNumbersLargeAbundantNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(33550335).getClassification()) + .isEqualTo(Classification.ABUNDANT); } @Disabled("Remove to run test") @Test - @DisplayName("Perfect square abundant number is classified correctly") - public void testPerfectSquareAbundantNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(196).getClassification()).isEqualTo(Classification.ABUNDANT); + @DisplayName("Deficient numbers -> Smallest prime deficient number is classified correctly") + public void deficientNumbersSmallestPrimeDeficientNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(2).getClassification()) + .isEqualTo(Classification.DEFICIENT); } @Disabled("Remove to run test") @Test - @DisplayName("Smallest prime deficient number is classified correctly") - public void testSmallestPrimeDeficientNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(2).getClassification()).isEqualTo(Classification.DEFICIENT); + @DisplayName("Deficient numbers -> Smallest non-prime deficient number is classified correctly") + public void deficientNumbersSmallestNonPrimeDeficientNumberIsClassifiedCorrec() { + assertThat(new NaturalNumber(4).getClassification()) + .isEqualTo(Classification.DEFICIENT); } @Disabled("Remove to run test") @Test - @DisplayName("Smallest non-prime deficient number is classified correctly") - public void testSmallestNonPrimeDeficientNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(4).getClassification()).isEqualTo(Classification.DEFICIENT); + @DisplayName("Deficient numbers -> Medium deficient number is classified correctly") + public void deficientNumbersMediumDeficientNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(32).getClassification()) + .isEqualTo(Classification.DEFICIENT); } @Disabled("Remove to run test") @Test - @DisplayName("Medium deficient number is classified as DEFICIENT") - public void testMediumDeficientNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(32).getClassification()).isEqualTo(Classification.DEFICIENT); + @DisplayName("Deficient numbers -> Large deficient number is classified correctly") + public void deficientNumbersLargeDeficientNumberIsClassifiedCorrectly() { + assertThat(new NaturalNumber(33550337).getClassification()) + .isEqualTo(Classification.DEFICIENT); } @Disabled("Remove to run test") @Test - @DisplayName("Large deficient number is classified as DEFICIENT") - public void testLargeDeficientNumberIsClassifiedCorrectly() { - assertThat(new NaturalNumber(33550337).getClassification()).isEqualTo(Classification.DEFICIENT); + @DisplayName("Deficient numbers -> Edge case (no factors other than itself) is classified correctly") + public void deficientNumbersEdgeCaseNoFactorsOtherThanItselfIsClassifiedCorre() { + assertThat(new NaturalNumber(1).getClassification()) + .isEqualTo(Classification.DEFICIENT); } @Disabled("Remove to run test") @Test - @DisplayName("Edge case (no factors other than itself) is classified correctly") - /* - * The number 1 has no proper divisors (https://en.wikipedia.org/wiki/Divisor#Further_notions_and_facts), and the - * additive identity is 0, so the aliquot sum of 1 should be 0. Hence 1 should be classified as deficient. - */ - public void testThatOneIsCorrectlyClassifiedAsDeficient() { - assertThat(new NaturalNumber(1).getClassification()).isEqualTo(Classification.DEFICIENT); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("Zero is rejected (as it is not a positive integer)") - public void testThatNonNegativeIntegerIsRejected() { + @DisplayName("Invalid inputs -> Zero is rejected (as it is not a positive integer)") + public void invalidInputsZeroIsRejectedAsItIsNotAPositiveInteger() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new NaturalNumber(0)) - .withMessage("You must supply a natural number (positive integer)"); + .isThrownBy(() -> new NaturalNumber(0)) + .withMessage("You must supply a natural number (positive integer)"); } @Disabled("Remove to run test") @Test - @DisplayName("Negative integer is rejected (as it is not a positive integer)") - public void testThatNegativeIntegerIsRejected() { + @DisplayName("Invalid inputs -> Negative integer is rejected (as it is not a positive integer)") + public void invalidInputsNegativeIntegerIsRejectedAsItIsNotAPositiveInteger() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new NaturalNumber(-1)) - .withMessage("You must supply a natural number (positive integer)"); + .isThrownBy(() -> new NaturalNumber(-1)) + .withMessage("You must supply a natural number (positive integer)"); } } diff --git a/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java b/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java index 300415b65..2d121ebdf 100644 --- a/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java +++ b/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java @@ -10,20 +10,19 @@ public class PhoneNumberTest { @Test @DisplayName("cleans the number") public void cleansTheNumber() { - String expectedNumber = "2234567890"; - String actualNumber = new PhoneNumber("(223) 456-7890").getNumber(); - assertThat(actualNumber).isEqualTo(expectedNumber); + assertThat(new PhoneNumber("(223) 456-7890").getNumber()) + .isEqualTo("2234567890"); + } @Disabled("Remove to run test") @Test @DisplayName("cleans numbers with dots") public void cleansNumbersWithDots() { - String expectedNumber = "2234567890"; - String actualNumber = new PhoneNumber("223.456.7890").getNumber(); - assertThat(actualNumber).isEqualTo(expectedNumber); + assertThat(new PhoneNumber("223.456.7890").getNumber()) + .isEqualTo("2234567890"); } @@ -31,10 +30,10 @@ public void cleansNumbersWithDots() { @Test @DisplayName("cleans numbers with multiple spaces") public void cleansNumbersWithMultipleSpaces() { - String expectedNumber = "2234567890"; - String actualNumber = new PhoneNumber("223 456 7890 ").getNumber(); - assertThat(actualNumber).isEqualTo(expectedNumber); + assertThat(new PhoneNumber("223 456 7890 ").getNumber()) + .isEqualTo("2234567890"); + } @Disabled("Remove to run test") @@ -45,134 +44,159 @@ public void invalidWhen9Digits() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("123456789")) .withMessage("must not be fewer than 10 digits"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid when 11 digits does not start with a 1") - public void invalidWhen11DigitsDoesNotStartWith1() { + public void invalidWhen11DigitsDoesNotStartWithA1() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("22234567890")) .withMessage("11 digits must start with 1"); + } @Disabled("Remove to run test") @Test @DisplayName("valid when 11 digits and starting with 1") public void validWhen11DigitsAndStartingWith1() { - String expectedNumber = "2234567890"; - String actualNumber = new PhoneNumber("12234567890").getNumber(); - assertThat(actualNumber).isEqualTo(expectedNumber); + assertThat(new PhoneNumber("12234567890").getNumber()) + .isEqualTo("2234567890"); + } @Disabled("Remove to run test") @Test @DisplayName("valid when 11 digits and starting with 1 even with punctuation") public void validWhen11DigitsAndStartingWith1EvenWithPunctuation() { - String expectedNumber = "2234567890"; - String actualNumber = new PhoneNumber("+1 (223) 456-7890").getNumber(); - assertThat(actualNumber).isEqualTo(expectedNumber); + assertThat(new PhoneNumber("+1 (223) 456-7890").getNumber()) + .isEqualTo("2234567890"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid when more than 11 digits") public void invalidWhenMoreThan11Digits() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("321234567890")) .withMessage("must not be greater than 11 digits"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid with letters") public void invalidWithLetters() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("523-abc-7890")) .withMessage("letters not permitted"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid with punctuations") public void invalidWithPunctuations() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("523-@:!-7890")) .withMessage("punctuations not permitted"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 0") public void invalidIfAreaCodeStartsWith0() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(023) 456-7890")) .withMessage("area code cannot start with zero"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 1") public void invalidIfAreaCodeStartsWith1() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(123) 456-7890")) .withMessage("area code cannot start with one"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 0") public void invalidIfExchangeCodeStartsWith0() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(223) 056-7890")) .withMessage("exchange code cannot start with zero"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 1") public void invalidIfExchangeCodeStartsWith1() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(223) 156-7890")) .withMessage("exchange code cannot start with one"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 0 on valid 11-digit number") public void invalidIfAreaCodeStartsWith0OnValid11DigitNumber() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (023) 456-7890")) .withMessage("area code cannot start with zero"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 1 on valid 11-digit number") public void invalidIfAreaCodeStartsWith1OnValid11DigitNumber() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (123) 456-7890")) .withMessage("area code cannot start with one"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 0 on valid 11-digit number") public void invalidIfExchangeCodeStartsWith0OnValid11DigitNumber() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (223) 056-7890")) .withMessage("exchange code cannot start with zero"); + } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 1 on valid 11-digit number") public void invalidIfExchangeCodeStartsWith1OnValid11DigitNumber() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (223) 156-7890")) .withMessage("exchange code cannot start with one"); + } + } diff --git a/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java index 791302fa3..5024b1430 100644 --- a/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java +++ b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java @@ -3,19 +3,37 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class PiecingItTogetherTest { + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-9; + private void assertJigsawInfoEquals(JigsawInfo actual, JigsawInfo expected) { + assertThat(actual.getPieces()).isEqualTo(expected.getPieces()); + assertThat(actual.getBorder()).isEqualTo(expected.getBorder()); + assertThat(actual.getInside()).isEqualTo(expected.getInside()); + assertThat(actual.getRows()).isEqualTo(expected.getRows()); + assertThat(actual.getColumns()).isEqualTo(expected.getColumns()); + assertThat(actual.getFormat()).isEqualTo(expected.getFormat()); + + Double actualAspect = actual.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in actual result")); + Double expectedAspect = expected.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in expected result")); + + assertThat(actualAspect).isCloseTo(expectedAspect, + org.assertj.core.api.Assertions.within(DOUBLE_EQUALITY_TOLERANCE)); + } + @Test @DisplayName("1000 pieces puzzle with 1.6 aspect ratio") - public void test1000PiecesWithAspectRatio() { + public void test1000PiecesPuzzleWith16AspectRatio() { + JigsawInfo input = new JigsawInfo.Builder() .pieces(1000) .aspectRatio(1.6) .build(); - JigsawInfo expected = new JigsawInfo.Builder() .pieces(1000) .border(126) @@ -25,20 +43,20 @@ public void test1000PiecesWithAspectRatio() { .aspectRatio(1.6) .format("landscape") .build(); - JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); + } @Disabled("Remove to run test") @Test @DisplayName("square puzzle with 32 rows") - public void testSquarePuzzleWith32Rows() { + public void squarePuzzleWith32Rows() { + JigsawInfo input = new JigsawInfo.Builder() .rows(32) .format("square") .build(); - JigsawInfo expected = new JigsawInfo.Builder() .pieces(1024) .border(124) @@ -48,20 +66,20 @@ public void testSquarePuzzleWith32Rows() { .aspectRatio(1.0) .format("square") .build(); - JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); + } @Disabled("Remove to run test") @Test @DisplayName("400 pieces square puzzle with only inside pieces and aspect ratio") - public void testInsideAndAspectRatioOnly() { + public void test400PiecesSquarePuzzleWithOnlyInsidePiecesAndAspectRatio() { + JigsawInfo input = new JigsawInfo.Builder() .inside(324) .aspectRatio(1.0) .build(); - JigsawInfo expected = new JigsawInfo.Builder() .pieces(400) .border(76) @@ -71,20 +89,20 @@ public void testInsideAndAspectRatioOnly() { .aspectRatio(1.0) .format("square") .build(); - JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); + } @Disabled("Remove to run test") @Test - @DisplayName("1500 pieces landscape puzzle with 30 rows and 1.6 aspect ratio") - public void testLandscape1500WithRowsAndAspect() { + @DisplayName("1500 pieces landscape puzzle with 30 rows and 5:3 aspect ratio") + public void test1500PiecesLandscapePuzzleWith30RowsAnd53AspectRatio() { + JigsawInfo input = new JigsawInfo.Builder() .rows(30) .aspectRatio(1.6666666666666667) .build(); - JigsawInfo expected = new JigsawInfo.Builder() .pieces(1500) .border(156) @@ -94,21 +112,21 @@ public void testLandscape1500WithRowsAndAspect() { .aspectRatio(1.6666666666666667) .format("landscape") .build(); - JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); + } @Disabled("Remove to run test") @Test @DisplayName("300 pieces portrait puzzle with 70 border pieces") - public void test300PiecesPortraitWithBorder() { + public void test300PiecesPortraitPuzzleWith70BorderPieces() { + JigsawInfo input = new JigsawInfo.Builder() .pieces(300) .border(70) .format("portrait") .build(); - JigsawInfo expected = new JigsawInfo.Builder() .pieces(300) .border(70) @@ -118,58 +136,40 @@ public void test300PiecesPortraitWithBorder() { .aspectRatio(0.48) .format("portrait") .build(); - JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); + } @Disabled("Remove to run test") @Test @DisplayName("puzzle with insufficient data") - public void testInsufficientData() { + public void puzzleWithInsufficientData() { + JigsawInfo input = new JigsawInfo.Builder() .pieces(1500) .format("landscape") .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) + .withMessage("Insufficient data"); - assertThatThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Insufficient data"); } @Disabled("Remove to run test") @Test @DisplayName("puzzle with contradictory data") - public void testContradictoryData() { + public void puzzleWithContradictoryData() { + JigsawInfo input = new JigsawInfo.Builder() .rows(100) .columns(1000) .format("square") .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) + .withMessage("Contradictory data"); - assertThatThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Contradictory data"); } - /** - * Helper to compare two JigsawInfo objects, - * allowing a small tolerance when comparing aspect ratio doubles. - */ - private void assertJigsawInfoEquals(JigsawInfo actual, JigsawInfo expected) { - assertThat(actual.getPieces()).isEqualTo(expected.getPieces()); - assertThat(actual.getBorder()).isEqualTo(expected.getBorder()); - assertThat(actual.getInside()).isEqualTo(expected.getInside()); - assertThat(actual.getRows()).isEqualTo(expected.getRows()); - assertThat(actual.getColumns()).isEqualTo(expected.getColumns()); - assertThat(actual.getFormat()).isEqualTo(expected.getFormat()); - - Double actualAspect = actual.getAspectRatio() - .orElseThrow(() -> new AssertionError("Missing aspect ratio in actual result")); - Double expectedAspect = expected.getAspectRatio() - .orElseThrow(() -> new AssertionError("Missing aspect ratio in expected result")); - - assertThat(actualAspect).isCloseTo(expectedAspect, - org.assertj.core.api.Assertions.within(DOUBLE_EQUALITY_TOLERANCE)); - } } diff --git a/exercises/practice/pig-latin/src/test/java/PigLatinTranslatorTest.java b/exercises/practice/pig-latin/src/test/java/PigLatinTranslatorTest.java index fd032e215..9a88d27d5 100644 --- a/exercises/practice/pig-latin/src/test/java/PigLatinTranslatorTest.java +++ b/exercises/practice/pig-latin/src/test/java/PigLatinTranslatorTest.java @@ -1,177 +1,185 @@ -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class PigLatinTranslatorTest { - - private PigLatinTranslator pigLatinTranslator; - - @BeforeEach - public void setup() { - pigLatinTranslator = new PigLatinTranslator(); - } +import static org.assertj.core.api.Assertions.assertThat; - @Test - @DisplayName("word beginning with a") - public void testWordBeginningWithA() { - assertThat(pigLatinTranslator.translate("apple")).isEqualTo("appleay"); - } +public class PigLatinTranslatorTest { - @Disabled("Remove to run test") @Test - @DisplayName("word beginning with e") - public void testWordBeginningWithE() { - assertThat(pigLatinTranslator.translate("ear")).isEqualTo("earay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with a") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithA() { + assertThat(new PigLatinTranslator().translate("apple")) + .isEqualTo("appleay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with i") - public void testWordBeginningWithI() { - assertThat(pigLatinTranslator.translate("igloo")).isEqualTo("iglooay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with e") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithE() { + assertThat(new PigLatinTranslator().translate("ear")) + .isEqualTo("earay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with o") - public void testWordBeginningWithO() { - assertThat(pigLatinTranslator.translate("object")).isEqualTo("objectay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with i") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithI() { + assertThat(new PigLatinTranslator().translate("igloo")) + .isEqualTo("iglooay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with u") - public void testWordBeginningWithU() { - assertThat(pigLatinTranslator.translate("under")).isEqualTo("underay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with o") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithO() { + assertThat(new PigLatinTranslator().translate("object")) + .isEqualTo("objectay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with a vowel and followed by a qu") - public void testWordBeginningWithVowelAndFollowedByQu() { - assertThat(pigLatinTranslator.translate("equal")).isEqualTo("equalay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with u") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithU() { + assertThat(new PigLatinTranslator().translate("under")) + .isEqualTo("underay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with p") - public void testWordBeginningWithP() { - assertThat(pigLatinTranslator.translate("pig")).isEqualTo("igpay"); + @DisplayName("ay is added to words that start with vowels -> word beginning with a " + + "vowel and followed by a qu") + public void ayIsAddedToWordsThatStartWithVowelsWordBeginningWithAVowelAndFoll() { + assertThat(new PigLatinTranslator().translate("equal")) + .isEqualTo("equalay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with k") - public void testWordBeginningWithK() { - assertThat(pigLatinTranslator.translate("koala")).isEqualTo("oalakay"); + @DisplayName("first letter and ay are moved to the end of words that start with " + + "consonants -> word beginning with p") + public void firstLetterAndAyAreMovedToTheEndOfWordsThatStartWithConsonantsWor() { + assertThat(new PigLatinTranslator().translate("pig")) + .isEqualTo("igpay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with x") - public void testWordBeginningWithX() { - assertThat(pigLatinTranslator.translate("xenon")).isEqualTo("enonxay"); + @DisplayName("first letter and ay are moved to the end of words that start with " + + "consonants -> word beginning with k") + public void firstLetterAndAyAreMovedToTheEndOfWordsThatStartWithConsonantsWor2() { + assertThat(new PigLatinTranslator().translate("koala")) + .isEqualTo("oalakay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with q without a following u") - public void testWordBeginningWithQWithoutAFollowingU() { - assertThat(pigLatinTranslator.translate("qat")).isEqualTo("atqay"); + @DisplayName("first letter and ay are moved to the end of words that start with " + + "consonants -> word beginning with x") + public void firstLetterAndAyAreMovedToTheEndOfWordsThatStartWithConsonantsWor3() { + assertThat(new PigLatinTranslator().translate("xenon")) + .isEqualTo("enonxay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with consonant and vowel containing qu") - public void testWordBeginningWithConsonantAndVowelContainingQu() { - assertThat(pigLatinTranslator.translate("liquid")).isEqualTo("iquidlay"); + @DisplayName("first letter and ay are moved to the end of words that start with " + + "consonants -> word beginning with q without a following u") + public void firstLetterAndAyAreMovedToTheEndOfWordsThatStartWithConsonantsWor4() { + assertThat(new PigLatinTranslator().translate("qat")) + .isEqualTo("atqay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with ch") - public void testChTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("chair")).isEqualTo("airchay"); + @DisplayName("some letter clusters are treated like a single consonant -> word beginning with ch") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith() { + assertThat(new PigLatinTranslator().translate("chair")) + .isEqualTo("airchay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with qu") - public void testQuTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("queen")).isEqualTo("eenquay"); + @DisplayName("some letter clusters are treated like a single consonant -> word beginning with qu") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith2() { + assertThat(new PigLatinTranslator().translate("queen")) + .isEqualTo("eenquay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with qu and a preceding consonant") - public void testQuAndAPrecedingConsonantTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("square")).isEqualTo("aresquay"); + @DisplayName("some letter clusters are treated like a single consonant -> word " + + "beginning with qu and a preceding consonant") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith3() { + assertThat(new PigLatinTranslator().translate("square")) + .isEqualTo("aresquay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with th") - public void testThTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("therapy")).isEqualTo("erapythay"); + @DisplayName("some letter clusters are treated like a single consonant -> word beginning with th") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith4() { + assertThat(new PigLatinTranslator().translate("therapy")) + .isEqualTo("erapythay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with thr") - public void testThrTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("thrush")).isEqualTo("ushthray"); + @DisplayName("some letter clusters are treated like a single consonant -> word beginning with thr") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith5() { + assertThat(new PigLatinTranslator().translate("thrush")) + .isEqualTo("ushthray"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with sch") - public void testSchTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("school")).isEqualTo("oolschay"); + @DisplayName("some letter clusters are treated like a single consonant -> word beginning with sch") + public void someLetterClustersAreTreatedLikeASingleConsonantWordBeginningWith6() { + assertThat(new PigLatinTranslator().translate("school")) + .isEqualTo("oolschay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with yt") - public void testYtTreatedLikeAVowelAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("yttria")).isEqualTo("yttriaay"); + @DisplayName("some letter clusters are treated like a single vowel -> word beginning with yt") + public void someLetterClustersAreTreatedLikeASingleVowelWordBeginningWithYt() { + assertThat(new PigLatinTranslator().translate("yttria")) + .isEqualTo("yttriaay"); } @Disabled("Remove to run test") @Test - @DisplayName("word beginning with xr") - public void testXrTreatedLikeAVowelAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("xray")).isEqualTo("xrayay"); + @DisplayName("some letter clusters are treated like a single vowel -> word beginning with xr") + public void someLetterClustersAreTreatedLikeASingleVowelWordBeginningWithXr() { + assertThat(new PigLatinTranslator().translate("xray")) + .isEqualTo("xrayay"); } @Disabled("Remove to run test") @Test - @DisplayName("y is treated like a consonant at the beginning of a word") - public void testYTreatedLikeAConsonantAtTheBeginningOfAWord() { - assertThat(pigLatinTranslator.translate("yellow")).isEqualTo("ellowyay"); + @DisplayName("position of y in a word determines if it is a consonant or a vowel -> " + + "y is treated like a consonant at the beginning of a word") + public void positionOfYInAWordDeterminesIfItIsAConsonantOrAVowelYIsTreatedLik() { + assertThat(new PigLatinTranslator().translate("yellow")) + .isEqualTo("ellowyay"); } @Disabled("Remove to run test") @Test - @DisplayName("y is treated like a vowel at the end of a consonant cluster") - public void testYTreatedLikeAVowelAtTheEndOfAConsonantCluster() { - assertThat(pigLatinTranslator.translate("rhythm")).isEqualTo("ythmrhay"); + @DisplayName("position of y in a word determines if it is a consonant or a vowel -> " + + "y is treated like a vowel at the end of a consonant cluster") + public void positionOfYInAWordDeterminesIfItIsAConsonantOrAVowelYIsTreatedLik2() { + assertThat(new PigLatinTranslator().translate("rhythm")) + .isEqualTo("ythmrhay"); } @Disabled("Remove to run test") @Test - @DisplayName("y as second letter in two letter word") - public void testYAsSecondLetterInTwoLetterWord() { - assertThat(pigLatinTranslator.translate("my")).isEqualTo("ymay"); + @DisplayName("position of y in a word determines if it is a consonant or a vowel -> " + + "y as second letter in two letter word") + public void positionOfYInAWordDeterminesIfItIsAConsonantOrAVowelYAsSecondLett() { + assertThat(new PigLatinTranslator().translate("my")) + .isEqualTo("ymay"); } - @Disabled("Remove to run test") - @Test - @DisplayName("a whole phrase") - public void testAWholePhrase() { - assertThat(pigLatinTranslator.translate("why do squids enjoy xrays")) - .isEqualTo("ywhay oday idssquay enjoyay xraysay"); - } } diff --git a/exercises/practice/poker/src/test/java/PokerTest.java b/exercises/practice/poker/src/test/java/PokerTest.java index 367b776df..9262cb53c 100644 --- a/exercises/practice/poker/src/test/java/PokerTest.java +++ b/exercises/practice/poker/src/test/java/PokerTest.java @@ -2,380 +2,356 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class PokerTest { + @Test @DisplayName("single hand always wins") - public void oneHand() { - String hand = "4S 5S 7H 8D JC"; - assertThat(new Poker(Collections.singletonList(hand)).getBestHands()) - .containsExactly(hand); + public void singleHandAlwaysWins() { + Poker poker = new Poker(List.of("4S 5S 7H 8D JC")); + List expected = List.of("4S 5S 7H 8D JC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("highest card out of all hands wins") - public void highestCardWins() { - String highest8 = "4D 5S 6S 8D 3C"; - String highest10 = "2S 4C 7S 9H 10H"; - String highestJ = "3S 4S 5D 6H JH"; - assertThat(new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands()) - .containsExactly(highestJ); + public void highestCardOutOfAllHandsWins() { + Poker poker = new Poker(List.of( + "4D 5S 6S 8D 3C", + "2S 4C 7S 9H 10H", + "3S 4S 5D 6H JH" + )); + List expected = List.of("3S 4S 5D 6H JH"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("a tie has multiple winners") - public void tieHasMultipleWinners() { - String highest8 = "4D 5S 6S 8D 3C"; - String highest10 = "2S 4C 7S 9H 10H"; - String highestJh = "3S 4S 5D 6H JH"; - String highestJd = "3H 4H 5C 6C JD"; - assertThat(new Poker(Arrays.asList(highest8, highest10, highestJh, highestJd)).getBestHands()) - .containsExactly(highestJh, highestJd); + public void aTieHasMultipleWinners() { + Poker poker = new Poker(List.of( + "4D 5S 6S 8D 3C", + "2S 4C 7S 9H 10H", + "3S 4S 5D 6H JH", + "3H 4H 5C 6C JD" + )); + List expected = List.of("3S 4S 5D 6H JH", "3H 4H 5C 6C JD"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test - @DisplayName("multiple hands with the same high cards, tie compares next highest ranked, down to last card") - public void sameHighCards() { - String nextHighest3 = "3S 5H 6S 8D 7H"; - String nextHighest2 = "2S 5D 6D 8C 7S"; - assertThat(new Poker(Arrays.asList(nextHighest3, nextHighest2)).getBestHands()) - .containsExactly(nextHighest3); + @DisplayName("multiple hands with the same high cards, tie compares next highest " + + "ranked, down to last card") + public void multipleHandsWithTheSameHighCardsTieComparesNextHighestRankedDown() { + Poker poker = new Poker(List.of("3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S")); + List expected = List.of("3S 5H 6S 8D 7H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("winning high card hand also has the lowest card") - public void winningWithLowestCard() { - String lowest2 = "2S 5H 6S 8D 7H"; - String lowest3 = "3S 4D 6D 8C 7S"; - assertThat(new Poker(Arrays.asList(lowest2, lowest3)).getBestHands()) - .containsExactly(lowest2); + public void winningHighCardHandAlsoHasTheLowestCard() { + Poker poker = new Poker(List.of("2S 5H 6S 8D 7H", "3S 4D 6D 8C 7S")); + List expected = List.of("2S 5H 6S 8D 7H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("one pair beats high card") - public void nothingVsOnePair() { - String nothing = "4S 5H 6C 8D KH"; - String pairOf4 = "2S 4H 6S 4D JH"; - assertThat(new Poker(Arrays.asList(nothing, pairOf4)).getBestHands()) - .containsExactly(pairOf4); + public void onePairBeatsHighCard() { + Poker poker = new Poker(List.of("4S 5H 6C 8D KH", "2S 4H 6S 4D JH")); + List expected = List.of("2S 4H 6S 4D JH"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("highest pair wins") - public void twoPairs() { - String pairOf2 = "4S 2H 6S 2D JH"; - String pairOf4 = "2S 4H 6C 4D JD"; - assertThat(new Poker(Arrays.asList(pairOf2, pairOf4)).getBestHands()) - .containsExactly(pairOf4); + public void highestPairWins() { + Poker poker = new Poker(List.of("4S 2H 6S 2D JH", "2S 4H 6C 4D JD")); + List expected = List.of("2S 4H 6C 4D JD"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have the same pair, high card wins") - public void samePair() { - String pairOf4Lower = "4H 4S AH JC 3D"; - String pairOf4Higher = "4C 4D AS 5D 6C"; - assertThat(new Poker(Arrays.asList(pairOf4Lower, pairOf4Higher)).getBestHands()) - .containsExactly(pairOf4Lower); + public void bothHandsHaveTheSamePairHighCardWins() { + Poker poker = new Poker(List.of("4H 4S AH JC 3D", "4C 4D AS 5D 6C")); + List expected = List.of("4H 4S AH JC 3D"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("two pairs beats one pair") - public void onePairVsDoublePair() { - String pairOf8 = "2S 8H 6S 8D JH"; - String doublePair = "4S 5H 4C 8C 5C"; - assertThat(new Poker(Arrays.asList(pairOf8, doublePair)).getBestHands()) - .containsExactly(doublePair); + public void twoPairsBeatsOnePair() { + Poker poker = new Poker(List.of("2S 8H 6S 8D JH", "4S 5H 4C 8C 5C")); + List expected = List.of("4S 5H 4C 8C 5C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have two pairs, highest ranked pair wins") - public void twoDoublePairs() { - String doublePair2And8 = "2S 8H 2D 8D 3H"; - String doublePair4And5 = "4S 5H 4C 8S 5D"; - assertThat(new Poker(Arrays.asList(doublePair2And8, doublePair4And5)).getBestHands()) - .containsExactly(doublePair2And8); + public void bothHandsHaveTwoPairsHighestRankedPairWins() { + Poker poker = new Poker(List.of("2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D")); + List expected = List.of("2S 8H 2D 8D 3H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have two pairs, with the same highest ranked pair, tie goes to low pair") - public void sameHighestPair() { - String doublePair2AndQ = "2S QS 2C QD JH"; - String doublePairJAndQ = "JD QH JS 8D QC"; - assertThat(new Poker(Arrays.asList(doublePairJAndQ, doublePair2AndQ)).getBestHands()) - .containsExactly(doublePairJAndQ); + public void bothHandsHaveTwoPairsWithTheSameHighestRankedPairTieGoesToLowPair() { + Poker poker = new Poker(List.of("2S QS 2C QD JH", "JD QH JS 8D QC")); + List expected = List.of("JD QH JS 8D QC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have two identically ranked pairs, tie goes to remaining card (kicker)") - public void identicallyRankedPairs() { - String kicker8 = "JD QH JS 8D QC"; - String kicker2 = "JS QS JC 2D QD"; - assertThat(new Poker(Arrays.asList(kicker8, kicker2)).getBestHands()) - .containsExactly(kicker8); + public void bothHandsHaveTwoIdenticallyRankedPairsTieGoesToRemainingCardKicke() { + Poker poker = new Poker(List.of("JD QH JS 8D QC", "JS QS JC 2D QD")); + List expected = List.of("JD QH JS 8D QC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have two pairs that add to the same value, win goes to highest pair") - public void twoPairsAddingToSameValue() { - String doublePair6And3 = "6S 6H 3S 3H AS"; - String doublePair7And2 = "7H 7S 2H 2S AC"; - assertThat(new Poker(Arrays.asList(doublePair6And3, doublePair7And2)).getBestHands()) - .containsExactly(doublePair7And2); + public void bothHandsHaveTwoPairsThatAddToTheSameValueWinGoesToHighestPair() { + Poker poker = new Poker(List.of("6S 6H 3S 3H AS", "7H 7S 2H 2S AC")); + List expected = List.of("7H 7S 2H 2S AC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("two pairs first ranked by largest pair") - public void rankedByLargestPair() { - String doublePairs5And4 = "5C 2S 5S 4H 4C"; - String doublePairs6And2 = "6S 2S 6H 7C 2C"; - assertThat(new Poker(Arrays.asList(doublePairs5And4, doublePairs6And2)).getBestHands()) - .containsExactly(doublePairs6And2); + public void twoPairsFirstRankedByLargestPair() { + Poker poker = new Poker(List.of("5C 2S 5S 4H 4C", "6S 2S 6H 7C 2C")); + List expected = List.of("6S 2S 6H 7C 2C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("three of a kind beats two pair") - public void doublePairVsThree() { - String doublePair2And8 = "2S 8H 2H 8D JH"; - String threeOf4 = "4S 5H 4C 8S 4H"; - assertThat(new Poker(Arrays.asList(doublePair2And8, threeOf4)).getBestHands()) - .containsExactly(threeOf4); + public void threeOfAKindBeatsTwoPair() { + Poker poker = new Poker(List.of("2S 8H 2H 8D JH", "4S 5H 4C 8S 4H")); + List expected = List.of("4S 5H 4C 8S 4H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have three of a kind, tie goes to highest ranked triplet") - public void twoThrees() { - String threeOf2 = "2S 2H 2C 8D JH"; - String threeOf1 = "4S AH AS 8C AD"; - assertThat(new Poker(Arrays.asList(threeOf2, threeOf1)).getBestHands()) - .containsExactly(threeOf1); + public void bothHandsHaveThreeOfAKindTieGoesToHighestRankedTriplet() { + Poker poker = new Poker(List.of("2S 2H 2C 8D JH", "4S AH AS 8C AD")); + List expected = List.of("4S AH AS 8C AD"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test - @DisplayName("with multiple decks, two players can have same three of a kind, ties go to highest remaining cards") - public void sameThreesMultipleDecks() { - String remainingCard7 = "5S AH AS 7C AD"; - String remainingCard8 = "4S AH AS 8C AD"; - assertThat(new Poker(Arrays.asList(remainingCard7, remainingCard8)).getBestHands()) - .containsExactly(remainingCard8); + @DisplayName("with multiple decks, two players can have same three of a kind, ties " + + "go to highest remaining cards") + public void withMultipleDecksTwoPlayersCanHaveSameThreeOfAKindTiesGoToHighest() { + Poker poker = new Poker(List.of("5S AH AS 7C AD", "4S AH AS 8C AD")); + List expected = List.of("4S AH AS 8C AD"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("a straight beats three of a kind") - public void threeVsStraight() { - String threeOf4 = "4S 5H 4C 8D 4H"; - String straight = "3S 4D 2S 6D 5C"; - assertThat(new Poker(Arrays.asList(threeOf4, straight)).getBestHands()) - .containsExactly(straight); + public void aStraightBeatsThreeOfAKind() { + Poker poker = new Poker(List.of("4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C")); + List expected = List.of("3S 4D 2S 6D 5C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces can end a straight (10 J Q K A)") - public void acesCanEndAStraight() { - String hand = "4S 5H 4C 8D 4H"; - String straightEndsA = "10D JH QS KD AC"; - assertThat(new Poker(Arrays.asList(hand, straightEndsA)).getBestHands()) - .containsExactly(straightEndsA); + public void acesCanEndAStraight10JQKA() { + Poker poker = new Poker(List.of("4S 5H 4C 8D 4H", "10D JH QS KD AC")); + List expected = List.of("10D JH QS KD AC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces can start a straight (A 2 3 4 5)") - public void acesCanStartAStraight() { - String hand = "4S 5H 4C 8D 4H"; - String straightStartA = "4D AH 3S 2D 5C"; - assertThat(new Poker(Arrays.asList(hand, straightStartA)).getBestHands()) - .containsExactly(straightStartA); + public void acesCanStartAStraightA2345() { + Poker poker = new Poker(List.of("4S 5H 4C 8D 4H", "4D AH 3S 2D 5C")); + List expected = List.of("4D AH 3S 2D 5C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces cannot be in the middle of a straight (Q K A 2 3)") - public void acesCannotBeInMiddleOfStraight() { - String hand = "2C 3D 7H 5H 2S"; - String straightMiddleA = "QS KH AC 2D 3S"; - assertThat(new Poker(Arrays.asList(hand, straightMiddleA)).getBestHands()) - .containsExactly(hand); + public void acesCannotBeInTheMiddleOfAStraightQKA23() { + Poker poker = new Poker(List.of("2C 3D 7H 5H 2S", "QS KH AC 2D 3S")); + List expected = List.of("2C 3D 7H 5H 2S"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands with a straight, tie goes to highest ranked card") - public void twoStraights() { - String straightTo8 = "4S 6C 7S 8D 5H"; - String straightTo9 = "5S 7H 8S 9D 6H"; - assertThat(new Poker(Arrays.asList(straightTo8, straightTo9)).getBestHands()) - .containsExactly(straightTo9); + public void bothHandsWithAStraightTieGoesToHighestRankedCard() { + Poker poker = new Poker(List.of("4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H")); + List expected = List.of("5S 7H 8S 9D 6H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("even though an ace is usually high, a 5-high straight is the lowest-scoring straight") - public void theLowestStraightStartsWithAce() { - String straight = "2H 3C 4D 5D 6H"; - String straightStartA = "4S AH 3S 2D 5H"; - assertThat(new Poker(Arrays.asList(straight, straightStartA)).getBestHands()) - .containsExactly(straight); + public void evenThoughAnAceIsUsuallyHighA5HighStraightIsTheLowestScoringStrai() { + Poker poker = new Poker(List.of("2H 3C 4D 5D 6H", "4S AH 3S 2D 5H")); + List expected = List.of("2H 3C 4D 5D 6H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("flush beats a straight") - public void straightVsFlush() { - String straightTo8 = "4C 6H 7D 8D 5H"; - String flushTo7 = "2S 4S 5S 6S 7S"; - assertThat(new Poker(Arrays.asList(straightTo8, flushTo7)).getBestHands()) - .containsExactly(flushTo7); + public void flushBeatsAStraight() { + Poker poker = new Poker(List.of("4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S")); + List expected = List.of("2S 4S 5S 6S 7S"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have a flush, tie goes to high card, down to the last one if necessary") - public void twoFlushs() { - String flushTo9 = "2H 7H 8H 9H 6H"; - String flushTo7 = "3S 5S 6S 7S 8S"; - assertThat(new Poker(Arrays.asList(flushTo9, flushTo7)).getBestHands()) - .containsExactly(flushTo9); + public void bothHandsHaveAFlushTieGoesToHighCardDownToTheLastOneIfNecessary() { + Poker poker = new Poker(List.of("2H 7H 8H 9H 6H", "3S 5S 6S 7S 8S")); + List expected = List.of("2H 7H 8H 9H 6H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("full house beats a flush") - public void flushVsFull() { - String flushTo8 = "3H 6H 7H 8H 5H"; - String full = "4S 5H 4C 5D 4H"; - assertThat(new Poker(Arrays.asList(full, flushTo8)).getBestHands()) - .containsExactly(full); + public void fullHouseBeatsAFlush() { + Poker poker = new Poker(List.of("3H 6H 7H 8H 5H", "4S 5H 4C 5D 4H")); + List expected = List.of("4S 5H 4C 5D 4H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have a full house, tie goes to highest-ranked triplet") - public void twoFulls() { - String fullOf4By9 = "4H 4S 4D 9S 9D"; - String fullOf5By8 = "5H 5S 5D 8S 8D"; - assertThat(new Poker(Arrays.asList(fullOf4By9, fullOf5By8)).getBestHands()) - .containsExactly(fullOf5By8); + public void bothHandsHaveAFullHouseTieGoesToHighestRankedTriplet() { + Poker poker = new Poker(List.of("4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D")); + List expected = List.of("5H 5S 5D 8S 8D"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test - @DisplayName("with multiple decks, both hands have a full house with the same triplet, tie goes to the pair") - public void twoFullssameThripletMultipleDecks() { - String fullOf5By9 = "5H 5S 5D 9S 9D"; - String fullOf5By8 = "5H 5S 5D 8S 8D"; - assertThat(new Poker(Arrays.asList(fullOf5By9, fullOf5By8)).getBestHands()) - .containsExactly(fullOf5By9); + @DisplayName("with multiple decks, both hands have a full house with the same " + + "triplet, tie goes to the pair") + public void withMultipleDecksBothHandsHaveAFullHouseWithTheSameTripletTieGoes() { + Poker poker = new Poker(List.of("5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D")); + List expected = List.of("5H 5S 5D 9S 9D"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("four of a kind beats a full house") - public void fullVsSquare() { - String full = "4S 5H 4D 5D 4H"; - String squareOf3 = "3S 3H 2S 3D 3C"; - assertThat(new Poker(Arrays.asList(full, squareOf3)).getBestHands()) - .containsExactly(squareOf3); + public void fourOfAKindBeatsAFullHouse() { + Poker poker = new Poker(List.of("4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C")); + List expected = List.of("3S 3H 2S 3D 3C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have four of a kind, tie goes to high quad") - public void twoSquares() { - String squareOf2 = "2S 2H 2C 8D 2D"; - String squareOf5 = "4S 5H 5S 5D 5C"; - assertThat(new Poker(Arrays.asList(squareOf2, squareOf5)).getBestHands()) - .containsExactly(squareOf5); + public void bothHandsHaveFourOfAKindTieGoesToHighQuad() { + Poker poker = new Poker(List.of("2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C")); + List expected = List.of("4S 5H 5S 5D 5C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test - @DisplayName("with multiple decks, both hands with identical four of a kind, tie determined by kicker") - public void sameSquaresMultipleDecks() { - String kicker2 = "3S 3H 2S 3D 3C"; - String kicker4 = "3S 3H 4S 3D 3C"; - assertThat(new Poker(Arrays.asList(kicker2, kicker4)).getBestHands()) - .containsExactly(kicker4); + @DisplayName("with multiple decks, both hands with identical four of a kind, tie " + + "determined by kicker") + public void withMultipleDecksBothHandsWithIdenticalFourOfAKindTieDeterminedBy() { + Poker poker = new Poker(List.of("3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C")); + List expected = List.of("3S 3H 4S 3D 3C"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("straight flush beats four of a kind") - public void squareVsStraightFlush() { - String squareOf5 = "4S 5H 5S 5D 5C"; - String straightFlushTo9 = "7S 8S 9S 6S 10S"; - assertThat(new Poker(Arrays.asList(squareOf5, straightFlushTo9)).getBestHands()) - .containsExactly(straightFlushTo9); + public void straightFlushBeatsFourOfAKind() { + Poker poker = new Poker(List.of("4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S")); + List expected = List.of("7S 8S 9S 6S 10S"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces can end a straight flush (10 J Q K A)") - public void acesEndingStraightFlush() { - String hand = "KC AH AS AD AC"; - String straightFlushEndingWithA = "10C JC QC KC AC"; - assertThat(new Poker(Arrays.asList(hand, straightFlushEndingWithA)).getBestHands()) - .containsExactly(straightFlushEndingWithA); + public void acesCanEndAStraightFlush10JQKA() { + Poker poker = new Poker(List.of("KC AH AS AD AC", "10C JC QC KC AC")); + List expected = List.of("10C JC QC KC AC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces can start a straight flush (A 2 3 4 5)") - public void acesStartingStraightFlush() { - String straightFlushStartingWithA = "4H AH 3H 2H 5H"; - String hand = "KS AH AS AD AC"; - assertThat(new Poker(Arrays.asList(straightFlushStartingWithA, hand)).getBestHands()) - .containsExactly(straightFlushStartingWithA); + public void acesCanStartAStraightFlushA2345() { + Poker poker = new Poker(List.of("KS AH AS AD AC", "4H AH 3H 2H 5H")); + List expected = List.of("4H AH 3H 2H 5H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("aces cannot be in the middle of a straight flush (Q K A 2 3)") - public void acesCannotBeInMiddleOfStraightFlush() { - String straightFlushWithAInMiddle = "QH KH AH 2H 3H"; - String hand = "2C AC QC 10C KC"; - assertThat(new Poker(Arrays.asList(straightFlushWithAInMiddle, hand)).getBestHands()) - .containsExactly(hand); + public void acesCannotBeInTheMiddleOfAStraightFlushQKA23() { + Poker poker = new Poker(List.of("2C AC QC 10C KC", "QH KH AH 2H 3H")); + List expected = List.of("2C AC QC 10C KC"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test @DisplayName("both hands have a straight flush, tie goes to highest-ranked card") - public void twoStraightFlushes() { - String straightFlushTo8 = "4H 6H 7H 8H 5H"; - String straightFlushTo9 = "5S 7S 8S 9S 6S"; - assertThat(new Poker(Arrays.asList(straightFlushTo8, straightFlushTo9)).getBestHands()) - .containsExactly(straightFlushTo9); + public void bothHandsHaveAStraightFlushTieGoesToHighestRankedCard() { + Poker poker = new Poker(List.of("4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S")); + List expected = List.of("5S 7S 8S 9S 6S"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } @Disabled("Remove to run test") @Test - @DisplayName("even though an ace is usually high, a 5-high straight flush is the lowest-scoring straight flush") - public void straightFlushTo5IsTheLowestScoring() { - String straightFlushTo6 = "2H 3H 4H 5H 6H"; - String straightFlushTo5 = "4D AD 3D 2D 5D"; - assertThat(new Poker(Arrays.asList(straightFlushTo6, straightFlushTo5)).getBestHands()) - .containsExactly(straightFlushTo6); + @DisplayName("even though an ace is usually high, a 5-high straight flush is the " + + "lowest-scoring straight flush") + public void evenThoughAnAceIsUsuallyHighA5HighStraightFlushIsTheLowestScoring() { + Poker poker = new Poker(List.of("2H 3H 4H 5H 6H", "4D AD 3D 2D 5D")); + List expected = List.of("2H 3H 4H 5H 6H"); + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); } + } diff --git a/exercises/practice/pov/src/test/java/PovTest.java b/exercises/practice/pov/src/test/java/PovTest.java index 844a9be8f..c16ef8c9f 100644 --- a/exercises/practice/pov/src/test/java/PovTest.java +++ b/exercises/practice/pov/src/test/java/PovTest.java @@ -10,8 +10,9 @@ public class PovTest { @Test - @DisplayName("Results in the same tree if the input tree is a singleton") - public void testFromPovGivenSingletonTree() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Results in " + + "the same tree if the input tree is a singleton") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeResultsInTheSameTreeIfT() { Tree tree = Tree.of("x"); Tree expected = Tree.of("x"); assertThat(tree.fromPov("x")).isEqualTo(expected); @@ -19,106 +20,128 @@ public void testFromPovGivenSingletonTree() { @Disabled("Remove to run test") @Test - @DisplayName("Can reroot a tree with a parent and one sibling") - public void testFromPovGivenTreeWithParentAndOneSibling() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Can reroot a " + + "tree with a parent and one sibling") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeCanRerootATreeWithAPare() { Tree tree = Tree.of("parent", - List.of(Tree.of("x"), - Tree.of("sibling"))); - + List.of( + Tree.of("x"), + Tree.of("sibling"))); Tree expected = Tree.of("x", - List.of(Tree.of("parent", - List.of(Tree.of("sibling"))))); + List.of( + Tree.of("parent", + List.of( + Tree.of("sibling"))))); assertThat(tree.fromPov("x")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Can reroot a tree with a parent and many siblings") - public void testFromPovGivenTreeWithParentAndManySibling() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Can reroot a " + + "tree with a parent and many siblings") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeCanRerootATreeWithAPare2() { Tree tree = Tree.of("parent", - List.of(Tree.of("x"), + List.of( + Tree.of("a"), + Tree.of("x"), + Tree.of("b"), + Tree.of("c"))); + Tree expected = Tree.of("x", + List.of( + Tree.of("parent", + List.of( Tree.of("a"), Tree.of("b"), - Tree.of("c"))); - - Tree expected = Tree.of("x", - List.of(Tree.of("parent", - List.of(Tree.of("a"), - Tree.of("b"), - Tree.of("c"))))); - + Tree.of("c"))))); assertThat(tree.fromPov("x")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("an reroot a tree with new root deeply nested in the tree") - public void testFromPovGivenTreeWithNewRootDeeplyNested() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Can reroot a " + + "tree with new root deeply nested in tree") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeCanRerootATreeWithNewRo() { Tree tree = Tree.of("level-0", - List.of(Tree.of("level-1", - List.of(Tree.of("level-2", - List.of(Tree.of("level-3", - List.of(Tree.of("x"))))))))); - + List.of( + Tree.of("level-1", + List.of( + Tree.of("level-2", + List.of( + Tree.of("level-3", + List.of( + Tree.of("x"))))))))); Tree expected = Tree.of("x", - List.of(Tree.of("level-3", - List.of(Tree.of("level-2", - List.of(Tree.of("level-1", - List.of(Tree.of("level-0"))))))))); - + List.of( + Tree.of("level-3", + List.of( + Tree.of("level-2", + List.of( + Tree.of("level-1", + List.of( + Tree.of("level-0"))))))))); assertThat(tree.fromPov("x")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Moves children of the new root to same level as former parent") - public void testFromPovGivenMovesChildrenOfNewRootToSameLevelAsFormerParent() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Moves " + + "children of the new root to same level as former parent") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeMovesChildrenOfTheNewRo() { Tree tree = Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))))); - + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))))); Tree expected = Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"), - Tree.of("parent"))); - + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"), + Tree.of("parent"))); assertThat(tree.fromPov("x")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Can reroot a complex tree with cousins") - public void testFromPovGivenComplexTreeWithCousins() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Can reroot a " + + "complex tree with cousins") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeCanRerootAComplexTreeWi() { Tree tree = Tree.of("grandparent", - List.of(Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))), - Tree.of("sibling-0"), - Tree.of("sibling-1"))), - Tree.of("uncle", - List.of(Tree.of("cousin-0"), - Tree.of("cousin-1"))))); - + List.of( + Tree.of("parent", + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))), + Tree.of("sibling-0"), + Tree.of("sibling-1"))), + Tree.of("uncle", + List.of( + Tree.of("cousin-0"), + Tree.of("cousin-1"))))); Tree expected = Tree.of("x", - List.of(Tree.of("kid-1"), - Tree.of("kid-0"), - Tree.of("parent", - List.of(Tree.of("sibling-0"), - Tree.of("sibling-1"), - Tree.of("grandparent", - List.of(Tree.of("uncle", - List.of(Tree.of("cousin-0"), - Tree.of("cousin-1"))))))))); - + List.of( + Tree.of("kid-1"), + Tree.of("kid-0"), + Tree.of("parent", + List.of( + Tree.of("sibling-0"), + Tree.of("sibling-1"), + Tree.of("grandparent", + List.of( + Tree.of("uncle", + List.of( + Tree.of("cousin-0"), + Tree.of("cousin-1"))))))))); assertThat(tree.fromPov("x")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Errors if target does not exist in a singleton tree") - public void testFromPovGivenNonExistentTargetInSingletonTree() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Errors if " + + "target does not exist in a singleton tree") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeErrorsIfTargetDoesNotEx() { Tree tree = Tree.of("x"); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> tree.fromPov("nonexistent")) @@ -127,15 +150,17 @@ public void testFromPovGivenNonExistentTargetInSingletonTree() { @Disabled("Remove to run test") @Test - @DisplayName("Errors if target does not exist in a larger tree") - public void testFromPovGivenNonExistentTargetInLargeTree() { + @DisplayName("Reroot a tree so that its root is the specified node. -> Errors if " + + "target does not exist in a large tree") + public void rerootATreeSoThatItsRootIsTheSpecifiedNodeErrorsIfTargetDoesNotEx2() { Tree tree = Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))), - Tree.of("sibling-0"), - Tree.of("sibling-1"))); - + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))), + Tree.of("sibling-0"), + Tree.of("sibling-1"))); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> tree.fromPov("nonexistent")) .withMessage("Tree could not be reoriented"); @@ -143,87 +168,93 @@ public void testFromPovGivenNonExistentTargetInLargeTree() { @Disabled("Remove to run test") @Test - @DisplayName("Can find path to parent") - public void testPathToCanFindPathToParent() { + @DisplayName("Given two nodes, find the path between them -> Can find path to parent") + public void givenTwoNodesFindThePathBetweenThemCanFindPathToParent() { Tree tree = Tree.of("parent", - List.of(Tree.of("x"), - Tree.of("sibling"))); - + List.of( + Tree.of("x"), + Tree.of("sibling"))); List expected = List.of("x", "parent"); assertThat(tree.pathTo("x", "parent")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - public void testPathToCanFindPathToSibling() { + @DisplayName("Given two nodes, find the path between them -> Can find path to sibling") + public void givenTwoNodesFindThePathBetweenThemCanFindPathToSibling() { Tree tree = Tree.of("parent", - List.of(Tree.of("a"), - Tree.of("x"), - Tree.of("b"), - Tree.of("c"))); - + List.of( + Tree.of("a"), + Tree.of("x"), + Tree.of("b"), + Tree.of("c"))); List expected = List.of("x", "parent", "b"); assertThat(tree.pathTo("x", "b")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Can find path to cousin") - public void testPathToCanFindPathToCousin() { + @DisplayName("Given two nodes, find the path between them -> Can find path to cousin") + public void givenTwoNodesFindThePathBetweenThemCanFindPathToCousin() { Tree tree = Tree.of("grandparent", - List.of(Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))), - Tree.of("sibling-0"), - Tree.of("sibling-1"))), - Tree.of("uncle", - List.of(Tree.of("cousin-0"), - Tree.of("cousin-1"))))); - + List.of( + Tree.of("parent", + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))), + Tree.of("sibling-0"), + Tree.of("sibling-1"))), + Tree.of("uncle", + List.of( + Tree.of("cousin-0"), + Tree.of("cousin-1"))))); List expected = List.of("x", "parent", "grandparent", "uncle", "cousin-1"); assertThat(tree.pathTo("x", "cousin-1")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Can find path not involving root") - public void testPathToCanFindPathNotEnvolvingRoot() { + @DisplayName("Given two nodes, find the path between them -> Can find path not involving root") + public void givenTwoNodesFindThePathBetweenThemCanFindPathNotInvolvingRoot() { Tree tree = Tree.of("grandparent", - List.of(Tree.of("parent", - List.of(Tree.of("x"), - Tree.of("sibling-0"), - Tree.of("sibling-1"))))); - + List.of( + Tree.of("parent", + List.of( + Tree.of("x"), + Tree.of("sibling-0"), + Tree.of("sibling-1"))))); List expected = List.of("x", "parent", "sibling-1"); assertThat(tree.pathTo("x", "sibling-1")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Can find path from nodes other than x") - public void testPathToCanFindPathFromNodesOtherThanX() { + @DisplayName("Given two nodes, find the path between them -> Can find path from nodes other than x") + public void givenTwoNodesFindThePathBetweenThemCanFindPathFromNodesOtherThanX() { Tree tree = Tree.of("parent", - List.of(Tree.of("a"), - Tree.of("x"), - Tree.of("b"), - Tree.of("c"))); - + List.of( + Tree.of("a"), + Tree.of("x"), + Tree.of("b"), + Tree.of("c"))); List expected = List.of("a", "parent", "c"); assertThat(tree.pathTo("a", "c")).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Errors if destination does not exist") - public void testPathWhenDestinationDoesNotExist() { + @DisplayName("Given two nodes, find the path between them -> Errors if destination does not exist") + public void givenTwoNodesFindThePathBetweenThemErrorsIfDestinationDoesNotExis() { Tree tree = Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))), - Tree.of("sibling-0"), - Tree.of("sibling-1"))); - + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))), + Tree.of("sibling-0"), + Tree.of("sibling-1"))); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> tree.pathTo("x", "nonexistent")) .withMessage("No path found"); @@ -231,15 +262,16 @@ public void testPathWhenDestinationDoesNotExist() { @Disabled("Remove to run test") @Test - @DisplayName("Errors if source does not exist") - public void testPathWhenSourceDoesNotExist() { + @DisplayName("Given two nodes, find the path between them -> Errors if source does not exist") + public void givenTwoNodesFindThePathBetweenThemErrorsIfSourceDoesNotExist() { Tree tree = Tree.of("parent", - List.of(Tree.of("x", - List.of(Tree.of("kid-0"), - Tree.of("kid-1"))), - Tree.of("sibling-0"), - Tree.of("sibling-1"))); - + List.of( + Tree.of("x", + List.of( + Tree.of("kid-0"), + Tree.of("kid-1"))), + Tree.of("sibling-0"), + Tree.of("sibling-1"))); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> tree.pathTo("nonexistent", "x")) .withMessage("No path found"); diff --git a/exercises/practice/prime-factors/src/test/java/PrimeFactorsCalculatorTest.java b/exercises/practice/prime-factors/src/test/java/PrimeFactorsCalculatorTest.java index d6f48a710..b01d0ca99 100644 --- a/exercises/practice/prime-factors/src/test/java/PrimeFactorsCalculatorTest.java +++ b/exercises/practice/prime-factors/src/test/java/PrimeFactorsCalculatorTest.java @@ -1,100 +1,106 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; public class PrimeFactorsCalculatorTest { - private PrimeFactorsCalculator primeFactorsCalculator; - - @BeforeEach - public void setUp() { - primeFactorsCalculator = new PrimeFactorsCalculator(); - } - @Test @DisplayName("no factors") - public void testNoFactors() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(1L)).isEmpty(); + public void noFactors() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(1L)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("prime number") - public void testPrimeNumber() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(2L)).containsExactly(2L); + public void primeNumber() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(2L)) + .isEqualTo(List.of(2L)); } @Disabled("Remove to run test") @Test @DisplayName("another prime number") - public void testAnotherPrimeNumber() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(3L)).containsExactly(3L); + public void anotherPrimeNumber() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(3L)) + .isEqualTo(List.of(3L)); } @Disabled("Remove to run test") @Test @DisplayName("square of a prime") - public void testSquareOfAPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(9L)).containsExactly(3L, 3L); + public void squareOfAPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(9L)) + .isEqualTo(List.of(3L, 3L)); } @Disabled("Remove to run test") @Test @DisplayName("product of first prime") - public void testProductOfFirstPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(4L)).containsExactly(2L, 2L); + public void productOfFirstPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(4L)) + .isEqualTo(List.of(2L, 2L)); } @Disabled("Remove to run test") @Test @DisplayName("cube of a prime") - public void testCubeOfAPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(8L)).containsExactly(2L, 2L, 2L); + public void cubeOfAPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(8L)) + .isEqualTo(List.of(2L, 2L, 2L)); } @Disabled("Remove to run test") @Test @DisplayName("product of second prime") - public void testProductOfSecondPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(625L)).containsExactly(5L, 5L, 5L, 5L); + public void productOfSecondPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(27L)) + .isEqualTo(List.of(3L, 3L, 3L)); } @Disabled("Remove to run test") @Test @DisplayName("product of third prime") - public void testProductOfThirdPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(27L)).containsExactly(3L, 3L, 3L); + public void productOfThirdPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(625L)) + .isEqualTo(List.of(5L, 5L, 5L, 5L)); } @Disabled("Remove to run test") @Test @DisplayName("product of first and second prime") - public void testProductOfFirstAndSecondPrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(6L)).containsExactly(2L, 3L); + public void productOfFirstAndSecondPrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(6L)) + .isEqualTo(List.of(2L, 3L)); } @Disabled("Remove to run test") @Test @DisplayName("product of primes and non-primes") - public void testProductOfPrimesAndNonPrimes() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(12L)).containsExactly(2L, 2L, 3L); + public void productOfPrimesAndNonPrimes() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(12L)) + .isEqualTo(List.of(2L, 2L, 3L)); } @Disabled("Remove to run test") @Test @DisplayName("product of primes") - public void testProductOfPrimes() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(901255L)).containsExactly(5L, 17L, 23L, 461L); + public void productOfPrimes() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(901255L)) + .isEqualTo(List.of(5L, 17L, 23L, 461L)); } @Disabled("Remove to run test") @Test @DisplayName("factors include a large prime") - public void testFactorsIncludingALargePrime() { - assertThat(primeFactorsCalculator.calculatePrimeFactorsOf(93819012551L)).containsExactly(11L, 9539L, 894119L); + public void factorsIncludeALargePrime() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf(93819012551L)) + .isEqualTo(List.of(11L, 9539L, 894119L)); } } diff --git a/exercises/practice/prism/src/test/java/PrismTest.java b/exercises/practice/prism/src/test/java/PrismTest.java index a4637c1bc..eb88f2766 100644 --- a/exercises/practice/prism/src/test/java/PrismTest.java +++ b/exercises/practice/prism/src/test/java/PrismTest.java @@ -7,297 +7,420 @@ import static org.assertj.core.api.Assertions.assertThat; public class PrismTest { + @Test @DisplayName("zero prisms") - public void testZeroPrisms() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + public void zeroPrisms() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of(); - assertThat(Prism.findSequence(laser, List.of())).isEmpty(); + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("one prism one hit") - public void testOnePrismOneHit() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of(new Prism.PrismInfo(1, 10, 0, 0)); + public void onePrismOneHit() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of(new Prism.PrismInfo(1, 10, 0, 0)); - assertThat(Prism.findSequence(laser, prisms)).containsExactly(1); + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of(1)); } @Disabled("Remove to run test") @Test - @DisplayName("one prism hits zero") - public void testOnePrismHitsZero() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of(new Prism.PrismInfo(1, -10, 0, 0)); + @DisplayName("one prism zero hits") + public void onePrismZeroHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of(new Prism.PrismInfo(1, -10, 0, 0)); - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("going up zero hits") - public void testGoingUpZeroHits() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 90); - final List prisms = List.of( - new Prism.PrismInfo(3, 0, -10, 0), - new Prism.PrismInfo(1, -10, 0, 0), - new Prism.PrismInfo(2, 10, 0, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + public void goingUpZeroHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 90); + List prisms = List.of( + new Prism.PrismInfo(3, 0, -10, 0), + new Prism.PrismInfo(1, -10, 0, 0), + new Prism.PrismInfo(2, 10, 0, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("going down zero hits") - public void testGoingDownZeroHits() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -90); - final List prisms = List.of( - new Prism.PrismInfo(1, 10, 0, 0), - new Prism.PrismInfo(2, 0, 10, 0), - new Prism.PrismInfo(3, -10, 0, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + public void goingDownZeroHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -90); + List prisms = List.of( + new Prism.PrismInfo(1, 10, 0, 0), + new Prism.PrismInfo(2, 0, 10, 0), + new Prism.PrismInfo(3, -10, 0, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("going left zero hits") - public void testGoingLeftZeroHits() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 180); - final List prisms = List.of( - new Prism.PrismInfo(2, 0, 10, 0), - new Prism.PrismInfo(3, 10, 0, 0), - new Prism.PrismInfo(1, 0, -10, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + public void goingLeftZeroHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 180); + List prisms = List.of( + new Prism.PrismInfo(2, 0, 10, 0), + new Prism.PrismInfo(3, 10, 0, 0), + new Prism.PrismInfo(1, 0, -10, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("negative angle") - public void testNegativeAngle() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -180); - final List prisms = List.of( - new Prism.PrismInfo(1, 0, -10, 0), - new Prism.PrismInfo(2, 0, 10, 0), - new Prism.PrismInfo(3, 10, 0, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + public void negativeAngle() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -180); + List prisms = List.of( + new Prism.PrismInfo(1, 0, -10, 0), + new Prism.PrismInfo(2, 0, 10, 0), + new Prism.PrismInfo(3, 10, 0, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("large angle") - public void testLargeAngle() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 2340); - final List prisms = List.of( - new Prism.PrismInfo(1, 10, 0, 0) - ); + public void largeAngle() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 2340); + List prisms = List.of(new Prism.PrismInfo(1, 10, 0, 0)); - assertThat(Prism.findSequence(laser, prisms)).isEmpty(); + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test - @DisplayName("upward reflection two hits") - public void testUpwardReflectionTwoHits() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of( - new Prism.PrismInfo(1, 10, 10, 0), - new Prism.PrismInfo(2, 10, 0, 90) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly(2, 1); + @DisplayName("upward refraction two hits") + public void upwardRefractionTwoHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of( + new Prism.PrismInfo(1, 10, 10, 0), + new Prism.PrismInfo(2, 10, 0, 90) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of(2, 1)); } @Disabled("Remove to run test") @Test - @DisplayName("downward reflection two hits") - public void testDownwardReflectionTwoHits() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of( - new Prism.PrismInfo(1, 10, 0, -90), - new Prism.PrismInfo(2, 10, -10, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly(1, 2); + @DisplayName("downward refraction two hits") + public void downwardRefractionTwoHits() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of( + new Prism.PrismInfo(1, 10, 0, -90), + new Prism.PrismInfo(2, 10, -10, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of(1, 2)); } @Disabled("Remove to run test") @Test @DisplayName("same prism twice") - public void testSamePrismTwice() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of( - new Prism.PrismInfo(2, 10, 0, 0), - new Prism.PrismInfo(1, 20, 0, -180) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly(2, 1, 2); + public void samePrismTwice() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of( + new Prism.PrismInfo(2, 10, 0, 0), + new Prism.PrismInfo(1, 20, 0, -180) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of(2, 1, 2)); } @Disabled("Remove to run test") @Test @DisplayName("simple path") - public void testSimplePath() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of( - new Prism.PrismInfo(3, 30, 10, 45), - new Prism.PrismInfo(1, 10, 10, -90), - new Prism.PrismInfo(2, 10, 0, 90), - new Prism.PrismInfo(4, 20, 0, 0) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly(2, 1, 3); + public void simplePath() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); + List prisms = List.of( + new Prism.PrismInfo(3, 30, 10, 45), + new Prism.PrismInfo(1, 10, 10, -90), + new Prism.PrismInfo(2, 10, 0, 90), + new Prism.PrismInfo(4, 20, 0, 0) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of(2, 1, 3)); } @Disabled("Remove to run test") @Test @DisplayName("multiple prisms floating point precision") - public void testMultiplePrismFloatingPointPrecision() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -6.429); - final List prisms = List.of( - new Prism.PrismInfo(26, 5.8, 73.4, 6.555), - new Prism.PrismInfo(24, 36.2, 65.2, -0.304), - new Prism.PrismInfo(20, 20.4, 82.8, 45.17), - new Prism.PrismInfo(31, -20.2, 48.8, 30.615), - new Prism.PrismInfo(30, 24.0, 0.6, 28.771), - new Prism.PrismInfo(29, 31.4, 79.4, 61.327), - new Prism.PrismInfo(28, 36.4, 31.4, -18.157), - new Prism.PrismInfo(22, 47.0, 57.8, 54.745), - new Prism.PrismInfo(38, 36.4, 79.2, 49.05), - new Prism.PrismInfo(10, 37.8, 55.2, 11.978), - new Prism.PrismInfo(18, -26.0, 42.6, 22.661), - new Prism.PrismInfo(25, 38.8, 76.2, 51.958), - new Prism.PrismInfo(2, 0.0, 42.4, -21.817), - new Prism.PrismInfo(35, 21.4, 44.8, -171.579), - new Prism.PrismInfo(7, 14.2, -1.6, 19.081), - new Prism.PrismInfo(33, 11.2, 44.4, -165.941), - new Prism.PrismInfo(11, 15.4, 82.6, 66.262), - new Prism.PrismInfo(16, 30.8, 6.6, 35.852), - new Prism.PrismInfo(15, -3.0, 79.2, 53.782), - new Prism.PrismInfo(4, 29.0, 75.4, 17.016), - new Prism.PrismInfo(23, 41.6, 59.8, 70.763), - new Prism.PrismInfo(8, -10.0, 15.8, -9.24), - new Prism.PrismInfo(13, 48.6, 51.8, 45.812), - new Prism.PrismInfo(1, 13.2, 77.0, 17.937), - new Prism.PrismInfo(34, -8.8, 36.8, -4.199), - new Prism.PrismInfo(21, 24.4, 75.8, 20.783), - new Prism.PrismInfo(17, -4.4, 74.6, 24.709), - new Prism.PrismInfo(9, 30.8, 41.8, -165.413), - new Prism.PrismInfo(32, 4.2, 78.6, 40.892), - new Prism.PrismInfo(37, -15.8, 47.0, 33.29), - new Prism.PrismInfo(6, 1.0, 80.6, 51.295), - new Prism.PrismInfo(36, -27.0, 47.8, 92.52), - new Prism.PrismInfo(14, -2.0, 34.4, -52.001), - new Prism.PrismInfo(5, 23.2, 80.2, 31.866), - new Prism.PrismInfo(27, -5.6, 32.8, -75.303), - new Prism.PrismInfo(12, -1.0, 0.2, 0.0), - new Prism.PrismInfo(3, -6.6, 3.2, 46.72), - new Prism.PrismInfo(19, -13.8, 24.2, -9.205) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly( - 7, 30, 16, 28, 13, 22, 23, 10, 9, 24, 25, 38, 29, 4, 35, 21, 5, 20, - 11, 1, 33, 26, 32, 6, 15, 17, 2, 14, 27, 34, 37, 31, 36, 18, 19, 8, 3, 12); + public void multiplePrismsFloatingPointPrecision() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, -6.429); + List prisms = List.of( + new Prism.PrismInfo(26, 5.8, 73.4, 6.555), + new Prism.PrismInfo(24, 36.2, 65.2, -0.304), + new Prism.PrismInfo(20, 20.4, 82.8, 45.17), + new Prism.PrismInfo(31, -20.2, 48.8, 30.615), + new Prism.PrismInfo(30, 24.0, 0.6, 28.771), + new Prism.PrismInfo(29, 31.4, 79.4, 61.327), + new Prism.PrismInfo(28, 36.4, 31.4, -18.157), + new Prism.PrismInfo(22, 47.0, 57.8, 54.745), + new Prism.PrismInfo(38, 36.4, 79.2, 49.05), + new Prism.PrismInfo(10, 37.8, 55.2, 11.978), + new Prism.PrismInfo(18, -26.0, 42.6, 22.661), + new Prism.PrismInfo(25, 38.8, 76.2, 51.958), + new Prism.PrismInfo(2, 0.0, 42.4, -21.817), + new Prism.PrismInfo(35, 21.4, 44.8, -171.579), + new Prism.PrismInfo(7, 14.2, -1.6, 19.081), + new Prism.PrismInfo(33, 11.2, 44.4, -165.941), + new Prism.PrismInfo(11, 15.4, 82.6, 66.262), + new Prism.PrismInfo(16, 30.8, 6.6, 35.852), + new Prism.PrismInfo(15, -3.0, 79.2, 53.782), + new Prism.PrismInfo(4, 29.0, 75.4, 17.016), + new Prism.PrismInfo(23, 41.6, 59.8, 70.763), + new Prism.PrismInfo(8, -10.0, 15.8, -9.24), + new Prism.PrismInfo(13, 48.6, 51.8, 45.812), + new Prism.PrismInfo(1, 13.2, 77.0, 17.937), + new Prism.PrismInfo(34, -8.8, 36.8, -4.199), + new Prism.PrismInfo(21, 24.4, 75.8, 20.783), + new Prism.PrismInfo(17, -4.4, 74.6, 24.709), + new Prism.PrismInfo(9, 30.8, 41.8, -165.413), + new Prism.PrismInfo(32, 4.2, 78.6, 40.892), + new Prism.PrismInfo(37, -15.8, 47.0, 33.29), + new Prism.PrismInfo(6, 1.0, 80.6, 51.295), + new Prism.PrismInfo(36, -27.0, 47.8, 92.52), + new Prism.PrismInfo(14, -2.0, 34.4, -52.001), + new Prism.PrismInfo(5, 23.2, 80.2, 31.866), + new Prism.PrismInfo(27, -5.6, 32.8, -75.303), + new Prism.PrismInfo(12, -1.0, 0.2, 0.0), + new Prism.PrismInfo(3, -6.6, 3.2, 46.72), + new Prism.PrismInfo(19, -13.8, 24.2, -9.205) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of( + 7, + 30, + 16, + 28, + 13, + 22, + 23, + 10, + 9, + 24, + 25, + 38, + 29, + 4, + 35, + 21, + 5, + 20, + 11, + 1, + 33, + 26, + 32, + 6, + 15, + 17, + 2, + 14, + 27, + 34, + 37, + 31, + 36, + 18, + 19, + 8, + 3, + 12 + )); } @Disabled("Remove to run test") @Test @DisplayName("complex path with multiple prisms floating point precision") - public void testComplexPathWithMultiplePrismFloatingPointPrecision() { - final Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0); - final List prisms = List.of( - new Prism.PrismInfo(46, 37.4, 20.6, -88.332), - new Prism.PrismInfo(72, -24.2, 23.4, -90.774), - new Prism.PrismInfo(25, 78.6, 7.8, 98.562), - new Prism.PrismInfo(60, -58.8, 31.6, 115.56), - new Prism.PrismInfo(22, 75.2, 28.0, 63.515), - new Prism.PrismInfo(2, 89.8, 27.8, 91.176), - new Prism.PrismInfo(23, 9.8, 30.8, 30.829), - new Prism.PrismInfo(69, 22.8, 20.6, -88.315), - new Prism.PrismInfo(44, -0.8, 15.6, -116.565), - new Prism.PrismInfo(36, -24.2, 8.2, -90.0), - new Prism.PrismInfo(53, -1.2, 0.0, 0.0), - new Prism.PrismInfo(52, 14.2, 24.0, -143.896), - new Prism.PrismInfo(5, -65.2, 21.6, 93.128), - new Prism.PrismInfo(66, 5.4, 15.6, 31.608), - new Prism.PrismInfo(51, -72.6, 21.0, -100.976), - new Prism.PrismInfo(65, 48.0, 10.2, 87.455), - new Prism.PrismInfo(21, -41.8, 0.0, 68.352), - new Prism.PrismInfo(18, -46.2, 19.2, -128.362), - new Prism.PrismInfo(10, 74.4, 0.4, 90.939), - new Prism.PrismInfo(15, 67.6, 0.4, 84.958), - new Prism.PrismInfo(35, 14.8, -0.4, 89.176), - new Prism.PrismInfo(1, 83.0, 0.2, 89.105), - new Prism.PrismInfo(68, 14.6, 28.0, -29.867), - new Prism.PrismInfo(67, 79.8, 18.6, -136.643), - new Prism.PrismInfo(38, 53.0, 14.6, -90.848), - new Prism.PrismInfo(31, -58.0, 6.6, -61.837), - new Prism.PrismInfo(74, -30.8, 0.4, 85.966), - new Prism.PrismInfo(48, -4.6, 10.0, -161.222), - new Prism.PrismInfo(12, 59.0, 5.0, -91.164), - new Prism.PrismInfo(33, -16.4, 18.4, 90.734), - new Prism.PrismInfo(4, 82.6, 27.6, 71.127), - new Prism.PrismInfo(75, -10.2, 30.6, -1.108), - new Prism.PrismInfo(28, 38.0, 0.0, 86.863), - new Prism.PrismInfo(11, 64.4, -0.2, 92.353), - new Prism.PrismInfo(9, -51.4, 31.6, 67.249), - new Prism.PrismInfo(26, -39.8, 30.8, 61.113), - new Prism.PrismInfo(30, -34.2, 0.6, 111.33), - new Prism.PrismInfo(56, -51.0, 0.2, 70.445), - new Prism.PrismInfo(41, -12.0, 0.0, 91.219), - new Prism.PrismInfo(24, 63.8, 14.4, 86.586), - new Prism.PrismInfo(70, -72.8, 13.4, -87.238), - new Prism.PrismInfo(3, 22.4, 7.0, -91.685), - new Prism.PrismInfo(13, 34.4, 7.0, 90.0), - new Prism.PrismInfo(16, -47.4, 11.4, -136.02), - new Prism.PrismInfo(6, 90.0, 0.2, 90.415), - new Prism.PrismInfo(54, 44.0, 27.8, 85.969), - new Prism.PrismInfo(32, -9.0, 0.0, 91.615), - new Prism.PrismInfo(8, -31.6, 30.8, 0.535), - new Prism.PrismInfo(39, -12.0, 8.2, 90.0), - new Prism.PrismInfo(14, -79.6, 32.4, 92.342), - new Prism.PrismInfo(42, 65.8, 20.8, -85.867), - new Prism.PrismInfo(40, -65.0, 14.0, 87.109), - new Prism.PrismInfo(45, 10.6, 18.8, 23.697), - new Prism.PrismInfo(71, -24.2, 18.6, -88.531), - new Prism.PrismInfo(7, -72.6, 6.4, -89.148), - new Prism.PrismInfo(62, -32.0, 24.8, -140.8), - new Prism.PrismInfo(49, 34.4, -0.2, 89.415), - new Prism.PrismInfo(63, 74.2, 12.6, -138.429), - new Prism.PrismInfo(59, 82.8, 13.0, -140.177), - new Prism.PrismInfo(34, -9.4, 23.2, -88.238), - new Prism.PrismInfo(76, -57.6, 0.0, 1.2), - new Prism.PrismInfo(43, 7.0, 0.0, 116.565), - new Prism.PrismInfo(20, 45.8, -0.2, 1.469), - new Prism.PrismInfo(37, -16.6, 13.2, 84.785), - new Prism.PrismInfo(58, -79.0, -0.2, 89.481), - new Prism.PrismInfo(50, -24.2, 12.8, -86.987), - new Prism.PrismInfo(64, 59.2, 10.2, -92.203), - new Prism.PrismInfo(61, -72.0, 26.4, -83.66), - new Prism.PrismInfo(47, 45.4, 5.8, -82.992), - new Prism.PrismInfo(17, -52.2, 17.8, -52.938), - new Prism.PrismInfo(57, -61.8, 32.0, 84.627), - new Prism.PrismInfo(29, 47.2, 28.2, 92.954), - new Prism.PrismInfo(27, -4.6, 0.2, 87.397), - new Prism.PrismInfo(55, -61.4, 26.4, 94.086), - new Prism.PrismInfo(73, -40.4, 13.4, -62.229), - new Prism.PrismInfo(19, 53.2, 20.6, -87.181) - ); - - assertThat(Prism.findSequence(laser, prisms)).containsExactly( - 43, 44, 66, 45, 52, 35, 49, 13, 3, 69, 46, 28, 20, 11, 24, 38, 19, 42, - 15, 10, 63, 25, 59, 1, 6, 2, 4, 67, 22, 29, 65, 64, 12, 47, 54, 68, - 23, 75, 8, 26, 18, 9, 60, 17, 31, 7, 70, 40, 5, 51, 61, 55, 57, 14, - 58, 76, 56, 16, 21, 30, 73, 62, 74, 41, 39, 36, 50, 37, 33, 71, 72, - 34, 32, 27, 48, 53 - ); + public void complexPathWithMultiplePrismsFloatingPointPrecision() { + Prism.LaserInfo laser = new Prism.LaserInfo(0, 0, 0.0); + List prisms = List.of( + new Prism.PrismInfo(46, 37.4, 20.6, -88.332), + new Prism.PrismInfo(72, -24.2, 23.4, -90.774), + new Prism.PrismInfo(25, 78.6, 7.8, 98.562), + new Prism.PrismInfo(60, -58.8, 31.6, 115.56), + new Prism.PrismInfo(22, 75.2, 28.0, 63.515), + new Prism.PrismInfo(2, 89.8, 27.8, 91.176), + new Prism.PrismInfo(23, 9.8, 30.8, 30.829), + new Prism.PrismInfo(69, 22.8, 20.6, -88.315), + new Prism.PrismInfo(44, -0.8, 15.6, -116.565), + new Prism.PrismInfo(36, -24.2, 8.2, -90.0), + new Prism.PrismInfo(53, -1.2, 0.0, 0.0), + new Prism.PrismInfo(52, 14.2, 24.0, -143.896), + new Prism.PrismInfo(5, -65.2, 21.6, 93.128), + new Prism.PrismInfo(66, 5.4, 15.6, 31.608), + new Prism.PrismInfo(51, -72.6, 21.0, -100.976), + new Prism.PrismInfo(65, 48.0, 10.2, 87.455), + new Prism.PrismInfo(21, -41.8, 0.0, 68.352), + new Prism.PrismInfo(18, -46.2, 19.2, -128.362), + new Prism.PrismInfo(10, 74.4, 0.4, 90.939), + new Prism.PrismInfo(15, 67.6, 0.4, 84.958), + new Prism.PrismInfo(35, 14.8, -0.4, 89.176), + new Prism.PrismInfo(1, 83.0, 0.2, 89.105), + new Prism.PrismInfo(68, 14.6, 28.0, -29.867), + new Prism.PrismInfo(67, 79.8, 18.6, -136.643), + new Prism.PrismInfo(38, 53.0, 14.6, -90.848), + new Prism.PrismInfo(31, -58.0, 6.6, -61.837), + new Prism.PrismInfo(74, -30.8, 0.4, 85.966), + new Prism.PrismInfo(48, -4.6, 10.0, -161.222), + new Prism.PrismInfo(12, 59.0, 5.0, -91.164), + new Prism.PrismInfo(33, -16.4, 18.4, 90.734), + new Prism.PrismInfo(4, 82.6, 27.6, 71.127), + new Prism.PrismInfo(75, -10.2, 30.6, -1.108), + new Prism.PrismInfo(28, 38.0, 0.0, 86.863), + new Prism.PrismInfo(11, 64.4, -0.2, 92.353), + new Prism.PrismInfo(9, -51.4, 31.6, 67.249), + new Prism.PrismInfo(26, -39.8, 30.8, 61.113), + new Prism.PrismInfo(30, -34.2, 0.6, 111.33), + new Prism.PrismInfo(56, -51.0, 0.2, 70.445), + new Prism.PrismInfo(41, -12.0, 0.0, 91.219), + new Prism.PrismInfo(24, 63.8, 14.4, 86.586), + new Prism.PrismInfo(70, -72.8, 13.4, -87.238), + new Prism.PrismInfo(3, 22.4, 7.0, -91.685), + new Prism.PrismInfo(13, 34.4, 7.0, 90.0), + new Prism.PrismInfo(16, -47.4, 11.4, -136.02), + new Prism.PrismInfo(6, 90.0, 0.2, 90.415), + new Prism.PrismInfo(54, 44.0, 27.8, 85.969), + new Prism.PrismInfo(32, -9.0, 0.0, 91.615), + new Prism.PrismInfo(8, -31.6, 30.8, 0.535), + new Prism.PrismInfo(39, -12.0, 8.2, 90.0), + new Prism.PrismInfo(14, -79.6, 32.4, 92.342), + new Prism.PrismInfo(42, 65.8, 20.8, -85.867), + new Prism.PrismInfo(40, -65.0, 14.0, 87.109), + new Prism.PrismInfo(45, 10.6, 18.8, 23.697), + new Prism.PrismInfo(71, -24.2, 18.6, -88.531), + new Prism.PrismInfo(7, -72.6, 6.4, -89.148), + new Prism.PrismInfo(62, -32.0, 24.8, -140.8), + new Prism.PrismInfo(49, 34.4, -0.2, 89.415), + new Prism.PrismInfo(63, 74.2, 12.6, -138.429), + new Prism.PrismInfo(59, 82.8, 13.0, -140.177), + new Prism.PrismInfo(34, -9.4, 23.2, -88.238), + new Prism.PrismInfo(76, -57.6, 0.0, 1.2), + new Prism.PrismInfo(43, 7.0, 0.0, 116.565), + new Prism.PrismInfo(20, 45.8, -0.2, 1.469), + new Prism.PrismInfo(37, -16.6, 13.2, 84.785), + new Prism.PrismInfo(58, -79.0, -0.2, 89.481), + new Prism.PrismInfo(50, -24.2, 12.8, -86.987), + new Prism.PrismInfo(64, 59.2, 10.2, -92.203), + new Prism.PrismInfo(61, -72.0, 26.4, -83.66), + new Prism.PrismInfo(47, 45.4, 5.8, -82.992), + new Prism.PrismInfo(17, -52.2, 17.8, -52.938), + new Prism.PrismInfo(57, -61.8, 32.0, 84.627), + new Prism.PrismInfo(29, 47.2, 28.2, 92.954), + new Prism.PrismInfo(27, -4.6, 0.2, 87.397), + new Prism.PrismInfo(55, -61.4, 26.4, 94.086), + new Prism.PrismInfo(73, -40.4, 13.4, -62.229), + new Prism.PrismInfo(19, 53.2, 20.6, -87.181) + ); + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo(List.of( + 43, + 44, + 66, + 45, + 52, + 35, + 49, + 13, + 3, + 69, + 46, + 28, + 20, + 11, + 24, + 38, + 19, + 42, + 15, + 10, + 63, + 25, + 59, + 1, + 6, + 2, + 4, + 67, + 22, + 29, + 65, + 64, + 12, + 47, + 54, + 68, + 23, + 75, + 8, + 26, + 18, + 9, + 60, + 17, + 31, + 7, + 70, + 40, + 5, + 51, + 61, + 55, + 57, + 14, + 58, + 76, + 56, + 16, + 21, + 30, + 73, + 62, + 74, + 41, + 39, + 36, + 50, + 37, + 33, + 71, + 72, + 34, + 32, + 27, + 48, + 53 + )); } + } diff --git a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java index 0eced2521..8aa023327 100644 --- a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java +++ b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java @@ -1,242 +1,326 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class ProteinTranslatorTest { - private ProteinTranslator proteinTranslator; - - @BeforeEach - public void setUp() { - proteinTranslator = new ProteinTranslator(); - } + private ProteinTranslator proteinTranslator = new ProteinTranslator(); @Test @DisplayName("Empty RNA sequence results in no proteins") - public void testEmptyRnaSequenceResultInNoproteins() { - assertThat(proteinTranslator.translate("")).isEmpty(); + public void emptyRnaSequenceResultsInNoProteins() { + + assertThat(proteinTranslator.translate("")) + .isEqualTo(List.of()); + } @Disabled("Remove to run test") @Test @DisplayName("Methionine RNA sequence") - public void testMethionineRnaSequence() { - assertThat(proteinTranslator.translate("AUG")).containsExactly("Methionine"); + public void methionineRnaSequence() { + + assertThat(proteinTranslator.translate("AUG")) + .isEqualTo(List.of("Methionine")); + } @Disabled("Remove to run test") @Test @DisplayName("Phenylalanine RNA sequence 1") - public void testPhenylalanineRnaSequence1() { - assertThat(proteinTranslator.translate("UUU")).containsExactly("Phenylalanine"); + public void phenylalanineRnaSequence1() { + + assertThat(proteinTranslator.translate("UUU")) + .isEqualTo(List.of("Phenylalanine")); + } @Disabled("Remove to run test") @Test @DisplayName("Phenylalanine RNA sequence 2") - public void testPhenylalanineRnaSequence2() { - assertThat(proteinTranslator.translate("UUC")).containsExactly("Phenylalanine"); + public void phenylalanineRnaSequence2() { + + assertThat(proteinTranslator.translate("UUC")) + .isEqualTo(List.of("Phenylalanine")); + } @Disabled("Remove to run test") @Test @DisplayName("Leucine RNA sequence 1") - public void testLeucineRnaSequence1() { - assertThat(proteinTranslator.translate("UUA")).containsExactly("Leucine"); + public void leucineRnaSequence1() { + + assertThat(proteinTranslator.translate("UUA")) + .isEqualTo(List.of("Leucine")); + } @Disabled("Remove to run test") @Test @DisplayName("Leucine RNA sequence 2") - public void testLeucineRnaSequence2() { - assertThat(proteinTranslator.translate("UUG")).containsExactly("Leucine"); + public void leucineRnaSequence2() { + + assertThat(proteinTranslator.translate("UUG")) + .isEqualTo(List.of("Leucine")); + } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 1") - public void testSerineRnaSequence1() { - assertThat(proteinTranslator.translate("UCU")).containsExactly("Serine"); + public void serineRnaSequence1() { + + assertThat(proteinTranslator.translate("UCU")) + .isEqualTo(List.of("Serine")); + } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 2") - public void testSerineRnaSequence2() { - assertThat(proteinTranslator.translate("UCC")).containsExactly("Serine"); + public void serineRnaSequence2() { + + assertThat(proteinTranslator.translate("UCC")) + .isEqualTo(List.of("Serine")); + } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 3") - public void testSerineRnaSequence3() { - assertThat(proteinTranslator.translate("UCA")).containsExactly("Serine"); + public void serineRnaSequence3() { + + assertThat(proteinTranslator.translate("UCA")) + .isEqualTo(List.of("Serine")); + } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 4") - public void testSerineRnaSequence4() { - assertThat(proteinTranslator.translate("UCG")).containsExactly("Serine"); + public void serineRnaSequence4() { + + assertThat(proteinTranslator.translate("UCG")) + .isEqualTo(List.of("Serine")); + } @Disabled("Remove to run test") @Test @DisplayName("Tyrosine RNA sequence 1") - public void testTyrosineRnaSequence1() { - assertThat(proteinTranslator.translate("UAU")).containsExactly("Tyrosine"); + public void tyrosineRnaSequence1() { + + assertThat(proteinTranslator.translate("UAU")) + .isEqualTo(List.of("Tyrosine")); + } @Disabled("Remove to run test") @Test @DisplayName("Tyrosine RNA sequence 2") - public void testTyrosineRnaSequence2() { - assertThat(proteinTranslator.translate("UAC")).containsExactly("Tyrosine"); + public void tyrosineRnaSequence2() { + + assertThat(proteinTranslator.translate("UAC")) + .isEqualTo(List.of("Tyrosine")); + } @Disabled("Remove to run test") @Test @DisplayName("Cysteine RNA sequence 1") - public void testCysteineRnaSequence1() { - assertThat(proteinTranslator.translate("UGU")).containsExactly("Cysteine"); + public void cysteineRnaSequence1() { + + assertThat(proteinTranslator.translate("UGU")) + .isEqualTo(List.of("Cysteine")); + } @Disabled("Remove to run test") @Test @DisplayName("Cysteine RNA sequence 2") - public void testCysteineRnaSequence2() { - assertThat(proteinTranslator.translate("UGC")).containsExactly("Cysteine"); + public void cysteineRnaSequence2() { + + assertThat(proteinTranslator.translate("UGC")) + .isEqualTo(List.of("Cysteine")); + } @Disabled("Remove to run test") @Test @DisplayName("Tryptophan RNA sequence") - public void testTryptophanRnaSequence1() { - assertThat(proteinTranslator.translate("UGG")).containsExactly("Tryptophan"); + public void tryptophanRnaSequence() { + + assertThat(proteinTranslator.translate("UGG")) + .isEqualTo(List.of("Tryptophan")); + } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 1") - public void testStopRnaSequence1() { - assertThat(proteinTranslator.translate("UAA")).isEmpty(); + public void stopCodonRnaSequence1() { + + assertThat(proteinTranslator.translate("UAA")) + .isEqualTo(List.of()); + } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 2") - public void testStopRnaSequence2() { - assertThat(proteinTranslator.translate("UAG")).isEmpty(); + public void stopCodonRnaSequence2() { + + assertThat(proteinTranslator.translate("UAG")) + .isEqualTo(List.of()); + } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 3") - public void testStopRnaSequence3() { - assertThat(proteinTranslator.translate("UGA")).isEmpty(); + public void stopCodonRnaSequence3() { + + assertThat(proteinTranslator.translate("UGA")) + .isEqualTo(List.of()); + } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two protein codons translates into proteins") - public void testSequenceOfTwoProteinCodonsTranslatesIntoProteins() { - assertThat(proteinTranslator.translate("UUUUUU")).containsExactly("Phenylalanine", "Phenylalanine"); + public void sequenceOfTwoProteinCodonsTranslatesIntoProteins() { + + assertThat(proteinTranslator.translate("UUUUUU")) + .isEqualTo(List.of("Phenylalanine", "Phenylalanine")); + } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two different protein codons translates into proteins") - public void testSequenceOfTwoDifferentProteinCodonsTranslatesIntoProteins() { - assertThat(proteinTranslator.translate("UUAUUG")).containsExactly("Leucine", "Leucine"); + public void sequenceOfTwoDifferentProteinCodonsTranslatesIntoProteins() { + + assertThat(proteinTranslator.translate("UUAUUG")) + .isEqualTo(List.of("Leucine", "Leucine")); + } @Disabled("Remove to run test") @Test @DisplayName("Translate RNA strand into correct protein list") - public void testTranslationOfRnaToProteinList() { + public void translateRnaStrandIntoCorrectProteinList() { + assertThat(proteinTranslator.translate("AUGUUUUGG")) - .containsExactly("Methionine", "Phenylalanine", "Tryptophan"); + .isEqualTo(List.of("Methionine", "Phenylalanine", "Tryptophan")); + } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at beginning of sequence") - public void testTranslationStopsIfStopCodonAtBeginning() { - assertThat(proteinTranslator.translate("UAGUGG")).isEmpty(); + public void translationStopsIfStopCodonAtBeginningOfSequence() { + + assertThat(proteinTranslator.translate("UAGUGG")) + .isEqualTo(List.of()); + } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at end of two-codon sequence") - public void testTranslationStopsIfStopCodonAtEnd1() { - assertThat(proteinTranslator.translate("UGGUAG")).containsExactly("Tryptophan"); + public void translationStopsIfStopCodonAtEndOfTwoCodonSequence() { + + assertThat(proteinTranslator.translate("UGGUAG")) + .isEqualTo(List.of("Tryptophan")); + } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at end of three-codon sequence") - public void testTranslationStopsIfStopCodonAtEnd2() { - assertThat(proteinTranslator.translate("AUGUUUUAA")).containsExactly("Methionine", "Phenylalanine"); + public void translationStopsIfStopCodonAtEndOfThreeCodonSequence() { + + assertThat(proteinTranslator.translate("AUGUUUUAA")) + .isEqualTo(List.of("Methionine", "Phenylalanine")); + } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon in middle of three-codon sequence") - public void testTranslationStopsIfStopCodonInMiddle1() { - assertThat(proteinTranslator.translate("UGGUAGUGG")).containsExactly("Tryptophan"); + public void translationStopsIfStopCodonInMiddleOfThreeCodonSequence() { + + assertThat(proteinTranslator.translate("UGGUAGUGG")) + .isEqualTo(List.of("Tryptophan")); + } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon in middle of six-codon sequence") - public void testTranslationStopsIfStopCodonInMiddle2() { + public void translationStopsIfStopCodonInMiddleOfSixCodonSequence() { + assertThat(proteinTranslator.translate("UGGUGUUAUUAAUGGUUU")) - .containsExactly("Tryptophan", "Cysteine", "Tyrosine"); + .isEqualTo(List.of("Tryptophan", "Cysteine", "Tyrosine")); + } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two non-STOP codons does not translate to a STOP codon") - public void testSequenceOfTwoNonStopCodonsDoNotTranslateToAStopCodon() { + public void sequenceOfTwoNonStopCodonsDoesNotTranslateToAStopCodon() { + assertThat(proteinTranslator.translate("AUGAUG")) - .containsExactly("Methionine", "Methionine"); + .isEqualTo(List.of("Methionine", "Methionine")); + } @Disabled("Remove to run test") @Test @DisplayName("Non-existing codon can't translate") - public void testNonExistingCodonCantTranslate() { + public void nonExistingCodonCanTTranslate() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("AAA")) .withMessage("Invalid codon"); + } @Disabled("Remove to run test") @Test @DisplayName("Unknown amino acids, not part of a codon, can't translate") - public void testUnknownAminoAcidsNotPartOfACodonCantTranslate() { + public void unknownAminoAcidsNotPartOfACodonCanTTranslate() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("XYZ")) .withMessage("Invalid codon"); + } @Disabled("Remove to run test") @Test @DisplayName("Incomplete RNA sequence can't translate") - public void testIncompleteRnaSequenceCantTranslate() { + public void incompleteRnaSequenceCanTTranslate() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("AUGU")) .withMessage("Invalid codon"); + } @Disabled("Remove to run test") @Test @DisplayName("Incomplete RNA sequence can translate if valid until a STOP codon") - public void testIncompleteRnaSequenceCanTranslateIfValidUntilAStopCodon() { - assertThat(proteinTranslator.translate("UUCUUCUAAUGGU")).containsExactly("Phenylalanine", "Phenylalanine"); + public void incompleteRnaSequenceCanTranslateIfValidUntilAStopCodon() { + + assertThat(proteinTranslator.translate("UUCUUCUAAUGGU")) + .isEqualTo(List.of("Phenylalanine", "Phenylalanine")); + } + } diff --git a/exercises/practice/proverb/src/test/java/ProverbTest.java b/exercises/practice/proverb/src/test/java/ProverbTest.java index 854a34b4b..3647ea15b 100644 --- a/exercises/practice/proverb/src/test/java/ProverbTest.java +++ b/exercises/practice/proverb/src/test/java/ProverbTest.java @@ -1,83 +1,76 @@ -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class ProverbTest { @Test @DisplayName("zero pieces") - public void zeroWordsAreGiven() { - String[] words = new String[0]; - - assertThat(new Proverb(words).recite()).isEqualTo(""); + public void zeroPieces() { + assertThat(new Proverb(new String[]{}).recite()) + .isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("one piece") - public void singlePieceOfProverb() { - String[] words = new String[]{"nail"}; - - assertThat(new Proverb(words).recite()) - .isEqualTo("And all for the want of a nail."); + public void onePiece() { + assertThat(new Proverb(new String[]{"nail"}).recite()) + .isEqualTo("And all for the want of a nail."); } @Disabled("Remove to run test") @Test @DisplayName("two pieces") - public void twoPiecesOfProverb() { - String[] words = new String[]{"nail", "shoe"}; - - assertThat(new Proverb(words).recite()) - .isEqualTo( - "For want of a nail the shoe was lost.\n" + - "And all for the want of a nail."); + public void twoPieces() { + assertThat(new Proverb(new String[]{"nail", "shoe"}).recite()) + .isEqualTo("For want of a nail the shoe was lost.\n" + + "And all for the want of a nail."); } @Disabled("Remove to run test") @Test @DisplayName("three pieces") - public void shortChainOfConsequences() { - String[] words = new String[]{"nail", "shoe", "horse"}; - - assertThat(new Proverb(words).recite()) - .isEqualTo( - "For want of a nail the shoe was lost.\n" + - "For want of a shoe the horse was lost.\n" + - "And all for the want of a nail."); + public void threePieces() { + assertThat(new Proverb(new String[]{"nail", "shoe", "horse"}).recite()) + .isEqualTo("For want of a nail the shoe was lost.\n" + + "For want of a shoe the horse was lost.\n" + + "And all for the want of a nail."); } @Disabled("Remove to run test") @Test @DisplayName("full proverb") public void fullProverb() { - String[] words = new String[]{"nail", "shoe", "horse", "rider", "message", "battle", "kingdom"}; - - assertThat(new Proverb(words).recite()) - .isEqualTo( - "For want of a nail the shoe was lost.\n" + - "For want of a shoe the horse was lost.\n" + - "For want of a horse the rider was lost.\n" + - "For want of a rider the message was lost.\n" + - "For want of a message the battle was lost.\n" + - "For want of a battle the kingdom was lost.\n" + - "And all for the want of a nail."); + assertThat(new Proverb(new String[]{ + "nail", + "shoe", + "horse", + "rider", + "message", + "battle", + "kingdom" + }).recite()) + .isEqualTo("For want of a nail the shoe was lost.\n" + + "For want of a shoe the horse was lost.\n" + + "For want of a horse the rider was lost.\n" + + "For want of a rider the message was lost.\n" + + "For want of a message the battle was lost.\n" + + "For want of a battle the kingdom was lost.\n" + + "And all for the want of a nail."); } @Disabled("Remove to run test") @Test @DisplayName("four pieces modernized") - public void fourPiecesModernizedProverb() { - String[] words = new String[]{"pin", "gun", "soldier", "battle"}; - - assertThat(new Proverb(words).recite()) - .isEqualTo( - "For want of a pin the gun was lost.\n" + - "For want of a gun the soldier was lost.\n" + - "For want of a soldier the battle was lost.\n" + - "And all for the want of a pin."); + public void fourPiecesModernized() { + assertThat(new Proverb(new String[]{"pin", "gun", "soldier", "battle"}).recite()) + .isEqualTo("For want of a pin the gun was lost.\n" + + "For want of a gun the soldier was lost.\n" + + "For want of a soldier the battle was lost.\n" + + "And all for the want of a pin."); } } diff --git a/exercises/practice/pythagorean-triplet/src/test/java/PythagoreanTripletTest.java b/exercises/practice/pythagorean-triplet/src/test/java/PythagoreanTripletTest.java index 50361fb3a..099e949fd 100644 --- a/exercises/practice/pythagorean-triplet/src/test/java/PythagoreanTripletTest.java +++ b/exercises/practice/pythagorean-triplet/src/test/java/PythagoreanTripletTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -13,13 +11,11 @@ public class PythagoreanTripletTest { @Test @DisplayName("triplets whose sum is 12") public void tripletsWhoseSumIs12() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(12) - .build(); - List expected - = Collections.singletonList(new PythagoreanTriplet(3, 4, 5)); + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(12) + .build(); + List expected = List.of(new PythagoreanTriplet(3, 4, 5)); assertThat(actual).isEqualTo(expected); } @@ -27,13 +23,11 @@ public void tripletsWhoseSumIs12() { @Test @DisplayName("triplets whose sum is 108") public void tripletsWhoseSumIs108() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(108) - .build(); - List expected - = Collections.singletonList(new PythagoreanTriplet(27, 36, 45)); + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(108) + .build(); + List expected = List.of(new PythagoreanTriplet(27, 36, 45)); assertThat(actual).isEqualTo(expected); } @@ -41,117 +35,78 @@ public void tripletsWhoseSumIs108() { @Test @DisplayName("triplets whose sum is 1000") public void tripletsWhoseSumIs1000() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .withFactorsLessThanOrEqualTo(1000) - .thatSumTo(1000) - .build(); - List expected - = Collections.singletonList(new PythagoreanTriplet(200, 375, 425)); + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(1000) + .build(); + List expected = List.of(new PythagoreanTriplet(200, 375, 425)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("no matching triplets for 1001") - public void tripletsWhoseSumIs1001() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(1001) - .build(); - List expected = Collections.emptyList(); + public void noMatchingTripletsFor1001() { + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(1001) + .build(); + List expected = List.of(); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("returns all matching triplets") - public void tripletsWhoseSumIs90() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(90) - .build(); - List expected - = Arrays.asList( - new PythagoreanTriplet(9, 40, 41), - new PythagoreanTriplet(15, 36, 39)); + public void returnsAllMatchingTriplets() { + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(90) + .build(); + List expected = List.of( + new PythagoreanTriplet(9, 40, 41), + new PythagoreanTriplet(15, 36, 39) + ); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("several matching triplets") - public void tripletsWhoseSumIs840() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(840) - .build(); - List expected - = Arrays.asList( - new PythagoreanTriplet(40, 399, 401), - new PythagoreanTriplet(56, 390, 394), - new PythagoreanTriplet(105, 360, 375), - new PythagoreanTriplet(120, 350, 370), - new PythagoreanTriplet(140, 336, 364), - new PythagoreanTriplet(168, 315, 357), - new PythagoreanTriplet(210, 280, 350), - new PythagoreanTriplet(240, 252, 348)); - assertThat(actual).isEqualTo(expected); - } - - @Disabled("Remove to run test") - @Test - public void tripletsWhoseSumIs840WithFactorsLessThanOrEqualTo370() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .withFactorsLessThanOrEqualTo(370) - .thatSumTo(840) - .build(); - List expected - = Arrays.asList( - new PythagoreanTriplet(120, 350, 370), - new PythagoreanTriplet(140, 336, 364), - new PythagoreanTriplet(168, 315, 357), - new PythagoreanTriplet(210, 280, 350), - new PythagoreanTriplet(240, 252, 348)); + public void severalMatchingTriplets() { + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(840) + .build(); + List expected = List.of( + new PythagoreanTriplet(40, 399, 401), + new PythagoreanTriplet(56, 390, 394), + new PythagoreanTriplet(105, 360, 375), + new PythagoreanTriplet(120, 350, 370), + new PythagoreanTriplet(140, 336, 364), + new PythagoreanTriplet(168, 315, 357), + new PythagoreanTriplet(210, 280, 350), + new PythagoreanTriplet(240, 252, 348) + ); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("triplets for large number") - public void tripletsWhoseSumIs30000() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .thatSumTo(30000) - .build(); - List expected - = Arrays.asList( - new PythagoreanTriplet(1200, 14375, 14425), - new PythagoreanTriplet(1875, 14000, 14125), - new PythagoreanTriplet(5000, 12000, 13000), - new PythagoreanTriplet(6000, 11250, 12750), - new PythagoreanTriplet(7500, 10000, 12500)); + public void tripletsForLargeNumber() { + List actual = PythagoreanTriplet + .makeTripletsList() + .thatSumTo(30000) + .build(); + List expected = List.of( + new PythagoreanTriplet(1200, 14375, 14425), + new PythagoreanTriplet(1875, 14000, 14125), + new PythagoreanTriplet(5000, 12000, 13000), + new PythagoreanTriplet(6000, 11250, 12750), + new PythagoreanTriplet(7500, 10000, 12500) + ); assertThat(actual).isEqualTo(expected); } - @Disabled("Remove to run test") - @Test - public void tripletsWhoseSumIs30000WithFactorsLessThanOrEqualTo12500() { - List actual - = PythagoreanTriplet - .makeTripletsList() - .withFactorsLessThanOrEqualTo(12500) - .thatSumTo(30000) - .build(); - List expected - = Arrays.asList(new PythagoreanTriplet(7500, 10000, 12500)); - assertThat(actual).isEqualTo(expected); - } } diff --git a/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java b/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java index c4f4f70d2..d028624f2 100644 --- a/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java +++ b/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java @@ -3,150 +3,175 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; - +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class QueenAttackCalculatorTest { @Test - @DisplayName("queen with a valid position") - public void testCreateQueenWithAValidPosition() { + @DisplayName("Test creation of Queens with valid and invalid positions -> queen with " + + "a valid position") + public void testCreationOfQueensWithValidAndInvalidPositionsQueenWithAValidPo() { + new Queen(2, 2); + } @Disabled("Remove to run test") @Test - @DisplayName("queen must have positive row") - public void testCreateQueenMustHavePositiveRow() { + @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + + "have positive row") + public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new Queen(-2, 2)) - .withMessage("Queen position must have positive row."); + .isThrownBy(() -> new Queen(-2, 2)); + } @Disabled("Remove to run test") @Test - @DisplayName("queen must have row on board") - public void testCreateQueenMustHaveRowOnBoard() { + @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + + "have row on board") + public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHaveRowO() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new Queen(8, 4)) - .withMessage("Queen position must have row <= 7."); + .isThrownBy(() -> new Queen(8, 4)); + } @Disabled("Remove to run test") @Test - @DisplayName("queen must have positive column") - public void testCreateQueenMustHavePositiveColumn() { + @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + + "have positive column") + public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi2() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new Queen(2, -2)) - .withMessage("Queen position must have positive column."); + .isThrownBy(() -> new Queen(2, -2)); + } @Disabled("Remove to run test") @Test - @DisplayName("queen must have column on board") - public void testCreateQueenMustHaveColumnOnBoard() { + @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + + "have column on board") + public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHaveColu() { + assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new Queen(4, 8)) - .withMessage("Queen position must have column <= 7."); + .isThrownBy(() -> new Queen(4, 8)); + } @Disabled("Remove to run test") @Test - @DisplayName("cannot attack") - public void testQueensCannotAttack() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(2, 4), new Queen(6, 6)); + @DisplayName("Test the ability of one queen to attack another -> cannot attack") + public void testTheAbilityOfOneQueenToAttackAnotherCannotAttack() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(2, 4), + new Queen(6, 6) + ); assertThat(calculator.canQueensAttackOneAnother()).isFalse(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on same row") - public void testQueensCanAttackOnTheSameRow() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(2, 4), new Queen(2, 6)); + @DisplayName("Test the ability of one queen to attack another -> can attack on same row") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSameRow() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(2, 4), + new Queen(2, 6) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on same column") - public void testQueensCanAttackOnTheSameColumn() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(4, 5), new Queen(2, 5)); + @DisplayName("Test the ability of one queen to attack another -> can attack on same column") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSameColumn() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(4, 5), + new Queen(2, 5) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on first diagonal") - public void testQueensCanAttackOnFirstDiagonal() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(2, 2), new Queen(0, 4)); + @DisplayName("Test the ability of one queen to attack another -> can attack on first diagonal") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnFirstDiagonal() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(2, 2), + new Queen(0, 4) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on second diagonal") - public void testQueensCanAttackOnSecondDiagonal() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(2, 2), new Queen(3, 1)); + @DisplayName("Test the ability of one queen to attack another -> can attack on second diagonal") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSecondDiagonal() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(2, 2), + new Queen(3, 1) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on third diagonal") - public void testQueensCanAttackOnThirdDiagonal() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(2, 2), new Queen(1, 1)); + @DisplayName("Test the ability of one queen to attack another -> can attack on third diagonal") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnThirdDiagonal() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(2, 2), + new Queen(1, 1) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName("can attack on fourth diagonal") - public void testQueensCanAttackOnFourthDiagonal() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(1, 7), new Queen(0, 6)); + @DisplayName("Test the ability of one queen to attack another -> can attack on fourth diagonal") + public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnFourthDiagonal() { + + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(1, 7), + new Queen(0, 6) + ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + } @Disabled("Remove to run test") @Test - @DisplayName( - "cannot attack if falling diagonals are only the same " + - "when reflected across the longest falling diagonal" - ) - public void testQueenCannotAttackIfFallingDiagonalsAreOnlyTheSameWhenReflectedAcrossTheLongestFallingDiagonal() { - QueenAttackCalculator calculator - = new QueenAttackCalculator(new Queen(4, 1), new Queen(2, 5)); + @DisplayName("Test the ability of one queen to attack another -> cannot attack if " + + "falling diagonals are only the same when reflected across the longest " + + "falling diagonal") + public void testTheAbilityOfOneQueenToAttackAnotherCannotAttackIfFallingDiago() { - assertThat(calculator.canQueensAttackOneAnother()).isFalse(); - } + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen(4, 1), + new Queen(2, 5) + ); - @Disabled("Remove to run test") - @Test - public void testNullPositionsNotAllowed() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new QueenAttackCalculator(null, new Queen(0, 7))) - .withMessage("You must supply valid positions for both Queens."); - } + assertThat(calculator.canQueensAttackOneAnother()).isFalse(); - @Disabled("Remove to run test") - @Test - public void testQueensMustNotOccupyTheSameSquare() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> new QueenAttackCalculator(new Queen(2, 2), new Queen(2, 2))) - .withMessage("Queens cannot occupy the same position."); } } diff --git a/exercises/practice/rail-fence-cipher/src/test/java/RailFenceCipherTest.java b/exercises/practice/rail-fence-cipher/src/test/java/RailFenceCipherTest.java index c18e6dd32..73e62e54f 100644 --- a/exercises/practice/rail-fence-cipher/src/test/java/RailFenceCipherTest.java +++ b/exercises/practice/rail-fence-cipher/src/test/java/RailFenceCipherTest.java @@ -6,58 +6,57 @@ public class RailFenceCipherTest { - private RailFenceCipher railFenceCipher; - @Test - @DisplayName("encode with two rails") - public void encodeWithTwoRails() { - railFenceCipher = new RailFenceCipher(2); - assertThat(railFenceCipher.getEncryptedData("XOXOXOXOXOXOXOXOXO")) - .isEqualTo("XXXXXXXXXOOOOOOOOO"); + @DisplayName("encode -> encode with two rails") + public void encodeEncodeWithTwoRails() { + assertThat(new RailFenceCipher(2) + .getEncryptedData("XOXOXOXOXOXOXOXOXO")) + .isEqualTo("XXXXXXXXXOOOOOOOOO"); } @Disabled("Remove to run test") @Test - @DisplayName("encode with three rails") - public void encodeWithThreeRails() { - railFenceCipher = new RailFenceCipher(3); - assertThat(railFenceCipher.getEncryptedData("WEAREDISCOVEREDFLEEATONCE")) - .isEqualTo("WECRLTEERDSOEEFEAOCAIVDEN"); + @DisplayName("encode -> encode with three rails") + public void encodeEncodeWithThreeRails() { + assertThat(new RailFenceCipher(3) + .getEncryptedData("WEAREDISCOVEREDFLEEATONCE")) + .isEqualTo("WECRLTEERDSOEEFEAOCAIVDEN"); } @Disabled("Remove to run test") @Test - @DisplayName("encode with ending in the middle") - public void encodeWithEndingInTheMiddle() { - railFenceCipher = new RailFenceCipher(4); - assertThat(railFenceCipher.getEncryptedData("EXERCISES")) - .isEqualTo("ESXIEECSR"); + @DisplayName("encode -> encode with ending in the middle") + public void encodeEncodeWithEndingInTheMiddle() { + assertThat(new RailFenceCipher(4) + .getEncryptedData("EXERCISES")) + .isEqualTo("ESXIEECSR"); } @Disabled("Remove to run test") @Test - @DisplayName("decode with three rails") - public void decodeWithThreeRails() { - railFenceCipher = new RailFenceCipher(3); - assertThat(railFenceCipher.getDecryptedData("TEITELHDVLSNHDTISEIIEA")) - .isEqualTo("THEDEVILISINTHEDETAILS"); + @DisplayName("decode -> decode with three rails") + public void decodeDecodeWithThreeRails() { + assertThat(new RailFenceCipher(3) + .getDecryptedData("TEITELHDVLSNHDTISEIIEA")) + .isEqualTo("THEDEVILISINTHEDETAILS"); } @Disabled("Remove to run test") @Test - @DisplayName("decode with five rails") - public void decodeWithFiveRails() { - railFenceCipher = new RailFenceCipher(5); - assertThat(railFenceCipher.getDecryptedData("EIEXMSMESAORIWSCE")) - .isEqualTo("EXERCISMISAWESOME"); + @DisplayName("decode -> decode with five rails") + public void decodeDecodeWithFiveRails() { + assertThat(new RailFenceCipher(5) + .getDecryptedData("EIEXMSMESAORIWSCE")) + .isEqualTo("EXERCISMISAWESOME"); } @Disabled("Remove to run test") @Test - @DisplayName("decode with six rails") - public void decodeWithSixRails() { - railFenceCipher = new RailFenceCipher(6); - assertThat(railFenceCipher.getDecryptedData("133714114238148966225439541018335470986172518171757571896261")) - .isEqualTo("112358132134558914423337761098715972584418167651094617711286"); + @DisplayName("decode -> decode with six rails") + public void decodeDecodeWithSixRails() { + assertThat(new RailFenceCipher(6) + .getDecryptedData("133714114238148966225439541018335470986172518171757571896261")) + .isEqualTo("112358132134558914423337761098715972584418167651094617711286"); } + } diff --git a/exercises/practice/raindrops/src/test/java/RaindropConverterTest.java b/exercises/practice/raindrops/src/test/java/RaindropConverterTest.java index 6499f2144..496672d8f 100644 --- a/exercises/practice/raindrops/src/test/java/RaindropConverterTest.java +++ b/exercises/practice/raindrops/src/test/java/RaindropConverterTest.java @@ -6,131 +6,147 @@ public class RaindropConverterTest { - private RaindropConverter raindropConverter = new RaindropConverter(); - @Test @DisplayName("the sound for 1 is 1") - public void soundFor1Is1() { - assertThat(raindropConverter.convert(1)).isEqualTo("1"); + public void theSoundFor1Is1() { + assertThat(new RaindropConverter().convert(1)) + .isEqualTo("1"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 3 is Pling") - public void soundFor3IsPling() { - assertThat(raindropConverter.convert(3)).isEqualTo("Pling"); + public void theSoundFor3IsPling() { + assertThat(new RaindropConverter().convert(3)) + .isEqualTo("Pling"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 5 is Plang") - public void soundFor5IsPlang() { - assertThat(raindropConverter.convert(5)).isEqualTo("Plang"); + public void theSoundFor5IsPlang() { + assertThat(new RaindropConverter().convert(5)) + .isEqualTo("Plang"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 7 is Plong") - public void soundFor7IsPlong() { - assertThat(raindropConverter.convert(7)).isEqualTo("Plong"); + public void theSoundFor7IsPlong() { + assertThat(new RaindropConverter().convert(7)) + .isEqualTo("Plong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 6 is Pling as it has a factor 3") - public void soundFor6IsPlingAsItHasFactor3() { - assertThat(raindropConverter.convert(6)).isEqualTo("Pling"); + public void theSoundFor6IsPlingAsItHasAFactor3() { + assertThat(new RaindropConverter().convert(6)) + .isEqualTo("Pling"); } @Disabled("Remove to run test") @Test @DisplayName("2 to the power 3 does not make a raindrop sound as 3 is the exponent not the base") - public void noSoundFor2Cubed() { - assertThat(raindropConverter.convert(8)).isEqualTo("8"); + public void test2ToThePower3DoesNotMakeARaindropSoundAs3IsTheExponentNotTheBa() { + assertThat(new RaindropConverter().convert(8)) + .isEqualTo("8"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 9 is Pling as it has a factor 3") - public void soundFor9IsPlingAsItHasFactor3() { - assertThat(raindropConverter.convert(9)).isEqualTo("Pling"); + public void theSoundFor9IsPlingAsItHasAFactor3() { + assertThat(new RaindropConverter().convert(9)) + .isEqualTo("Pling"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 10 is Plang as it has a factor 5") - public void soundFor10IsPlangAsItHasFactor5() { - assertThat(raindropConverter.convert(10)).isEqualTo("Plang"); + public void theSoundFor10IsPlangAsItHasAFactor5() { + assertThat(new RaindropConverter().convert(10)) + .isEqualTo("Plang"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 14 is Plong as it has a factor of 7") - public void soundFor14IsPlongAsItHasFactor7() { - assertThat(raindropConverter.convert(14)).isEqualTo("Plong"); + public void theSoundFor14IsPlongAsItHasAFactorOf7() { + assertThat(new RaindropConverter().convert(14)) + .isEqualTo("Plong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 15 is PlingPlang as it has factors 3 and 5") - public void soundFor15IsPlingPlangAsItHasFactors3And5() { - assertThat(raindropConverter.convert(15)).isEqualTo("PlingPlang"); + public void theSoundFor15IsPlingplangAsItHasFactors3And5() { + assertThat(new RaindropConverter().convert(15)) + .isEqualTo("PlingPlang"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 21 is PlingPlong as it has factors 3 and 7") - public void soundFor21IsPlingPlongAsItHasFactors3And7() { - assertThat(raindropConverter.convert(21)).isEqualTo("PlingPlong"); + public void theSoundFor21IsPlingplongAsItHasFactors3And7() { + assertThat(new RaindropConverter().convert(21)) + .isEqualTo("PlingPlong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 25 is Plang as it has a factor 5") - public void soundFor25IsPlangAsItHasFactor5() { - assertThat(raindropConverter.convert(25)).isEqualTo("Plang"); + public void theSoundFor25IsPlangAsItHasAFactor5() { + assertThat(new RaindropConverter().convert(25)) + .isEqualTo("Plang"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 27 is Pling as it has a factor 3") - public void soundFor27IsPlingAsItHasFactor3() { - assertThat(raindropConverter.convert(27)).isEqualTo("Pling"); + public void theSoundFor27IsPlingAsItHasAFactor3() { + assertThat(new RaindropConverter().convert(27)) + .isEqualTo("Pling"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 35 is PlangPlong as it has factors 5 and 7") - public void soundFor35IsPlangPlongAsItHasFactors5And7() { - assertThat(raindropConverter.convert(35)).isEqualTo("PlangPlong"); + public void theSoundFor35IsPlangplongAsItHasFactors5And7() { + assertThat(new RaindropConverter().convert(35)) + .isEqualTo("PlangPlong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 49 is Plong as it has a factor 7") - public void soundFor49IsPlongAsItHasFactor7() { - assertThat(raindropConverter.convert(49)).isEqualTo("Plong"); + public void theSoundFor49IsPlongAsItHasAFactor7() { + assertThat(new RaindropConverter().convert(49)) + .isEqualTo("Plong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 52 is 52") - public void noSoundFor52() { - assertThat(raindropConverter.convert(52)).isEqualTo("52"); + public void theSoundFor52Is52() { + assertThat(new RaindropConverter().convert(52)) + .isEqualTo("52"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 105 is PlingPlangPlong as it has factors 3, 5 and 7") - public void soundFor105IsPlingPlangPlongAsItHasFactors3And5And7() { - assertThat(raindropConverter.convert(105)).isEqualTo("PlingPlangPlong"); + public void theSoundFor105IsPlingplangplongAsItHasFactors35And7() { + assertThat(new RaindropConverter().convert(105)) + .isEqualTo("PlingPlangPlong"); } @Disabled("Remove to run test") @Test @DisplayName("the sound for 3125 is Plang as it has a factor 5") - public void soundFor3125IsPlangAsItHasFactor5() { - assertThat(raindropConverter.convert(3125)).isEqualTo("Plang"); + public void theSoundFor3125IsPlangAsItHasAFactor5() { + assertThat(new RaindropConverter().convert(3125)) + .isEqualTo("Plang"); } } diff --git a/exercises/practice/rational-numbers/src/test/java/RationalTest.java b/exercises/practice/rational-numbers/src/test/java/RationalTest.java index 91f8b3e49..7fdf4fd91 100644 --- a/exercises/practice/rational-numbers/src/test/java/RationalTest.java +++ b/exercises/practice/rational-numbers/src/test/java/RationalTest.java @@ -7,181 +7,199 @@ public class RationalTest { - // Helper methods - private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-8; private void assertDoublesEqual(double x, double y) { assertThat(x).isCloseTo(y, within(DOUBLE_EQUALITY_TOLERANCE)); } - // Tests - @Test - @DisplayName("Add two positive rational numbers") - public void testAddTwoPositiveRationalNumbers() { + @DisplayName("Arithmetic -> Addition -> Add two positive rational numbers") + public void arithmeticAdditionAddTwoPositiveRationalNumbers() { Rational expected = new Rational(7, 6); - Rational actual = new Rational(1, 2).add(new Rational(2, 3)); + Rational actual = new Rational(1, 2) + .add(new Rational(2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Add a positive rational number and a negative rational number") - public void testAddAPositiveRationalNumberAndANegativeRationalNumber() { + @DisplayName("Arithmetic -> Addition -> Add a positive rational number and a " + + "negative rational number") + public void arithmeticAdditionAddAPositiveRationalNumberAndANegativeRationalN() { Rational expected = new Rational(-1, 6); - Rational actual = new Rational(1, 2).add(new Rational(-2, 3)); + Rational actual = new Rational(1, 2) + .add(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Add two negative rational numbers") - public void testAddTwoNegativeRationalNumbers() { + @DisplayName("Arithmetic -> Addition -> Add two negative rational numbers") + public void arithmeticAdditionAddTwoNegativeRationalNumbers() { Rational expected = new Rational(-7, 6); - Rational actual = new Rational(-1, 2).add(new Rational(-2, 3)); + Rational actual = new Rational(-1, 2) + .add(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Add a rational number to its additive inverse") - public void testAddARationalNumberToItsAdditiveInverse() { + @DisplayName("Arithmetic -> Addition -> Add a rational number to its additive inverse") + public void arithmeticAdditionAddARationalNumberToItsAdditiveInverse() { Rational expected = new Rational(0, 1); - Rational actual = new Rational(1, 2).add(new Rational(-1, 2)); + Rational actual = new Rational(1, 2) + .add(new Rational(-1, 2)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Subtract two positive rational numbers") - public void testSubtractTwoPositiveRationalNumbers() { + @DisplayName("Arithmetic -> Subtraction -> Subtract two positive rational numbers") + public void arithmeticSubtractionSubtractTwoPositiveRationalNumbers() { Rational expected = new Rational(-1, 6); - Rational actual = new Rational(1, 2).subtract(new Rational(2, 3)); + Rational actual = new Rational(1, 2) + .subtract(new Rational(2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Subtract a positive rational number and a negative rational number") - public void testSubtractAPositiveRationalNumberAndANegativeRationalNumber() { + @DisplayName("Arithmetic -> Subtraction -> Subtract a positive rational number and a " + + "negative rational number") + public void arithmeticSubtractionSubtractAPositiveRationalNumberAndANegativeR() { Rational expected = new Rational(7, 6); - Rational actual = new Rational(1, 2).subtract(new Rational(-2, 3)); + Rational actual = new Rational(1, 2) + .subtract(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Subtract two negative rational numbers") - public void testSubtractTwoNegativeRationalNumbers() { + @DisplayName("Arithmetic -> Subtraction -> Subtract two negative rational numbers") + public void arithmeticSubtractionSubtractTwoNegativeRationalNumbers() { Rational expected = new Rational(1, 6); - Rational actual = new Rational(-1, 2).subtract(new Rational(-2, 3)); + Rational actual = new Rational(-1, 2) + .subtract(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Subtract a rational number from itself") - public void testSubtractARationalNumberFromItself() { + @DisplayName("Arithmetic -> Subtraction -> Subtract a rational number from itself") + public void arithmeticSubtractionSubtractARationalNumberFromItself() { Rational expected = new Rational(0, 1); - Rational actual = new Rational(1, 2).subtract(new Rational(1, 2)); + Rational actual = new Rational(1, 2) + .subtract(new Rational(1, 2)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply two positive rational numbers") - public void testMultiplyTwoPositiveRationalNumbers() { + @DisplayName("Arithmetic -> Multiplication -> Multiply two positive rational numbers") + public void arithmeticMultiplicationMultiplyTwoPositiveRationalNumbers() { Rational expected = new Rational(1, 3); - Rational actual = new Rational(1, 2).multiply(new Rational(2, 3)); + Rational actual = new Rational(1, 2) + .multiply(new Rational(2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply a negative rational number by a positive rational number") - public void testMultiplyANegativeRationalNumberByAPositiveRationalNumber() { + @DisplayName("Arithmetic -> Multiplication -> Multiply a negative rational number by " + + "a positive rational number") + public void arithmeticMultiplicationMultiplyANegativeRationalNumberByAPositiv() { Rational expected = new Rational(-1, 3); - Rational actual = new Rational(-1, 2).multiply(new Rational(2, 3)); + Rational actual = new Rational(-1, 2) + .multiply(new Rational(2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply two negative rational numbers") - public void testMultiplyTwoNegativeRationalNumbers() { + @DisplayName("Arithmetic -> Multiplication -> Multiply two negative rational numbers") + public void arithmeticMultiplicationMultiplyTwoNegativeRationalNumbers() { Rational expected = new Rational(1, 3); - Rational actual = new Rational(-1, 2).multiply(new Rational(-2, 3)); + Rational actual = new Rational(-1, 2) + .multiply(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply a rational number by its reciprocal") - public void testMultiplyARationalNumberByItsReciprocal() { + @DisplayName("Arithmetic -> Multiplication -> Multiply a rational number by its reciprocal") + public void arithmeticMultiplicationMultiplyARationalNumberByItsReciprocal() { Rational expected = new Rational(1, 1); - Rational actual = new Rational(1, 2).multiply(new Rational(2, 1)); + Rational actual = new Rational(1, 2) + .multiply(new Rational(2, 1)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply a rational number by 1") - public void testMultiplyARationalNumberByOne() { + @DisplayName("Arithmetic -> Multiplication -> Multiply a rational number by 1") + public void arithmeticMultiplicationMultiplyARationalNumberBy1() { Rational expected = new Rational(1, 2); - Rational actual = new Rational(1, 2).multiply(new Rational(1, 1)); + Rational actual = new Rational(1, 2) + .multiply(new Rational(1, 1)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Multiply a rational number by 0") - public void testMultiplyARationalNumberByZero() { + @DisplayName("Arithmetic -> Multiplication -> Multiply a rational number by 0") + public void arithmeticMultiplicationMultiplyARationalNumberBy0() { Rational expected = new Rational(0, 1); - Rational actual = new Rational(1, 2).multiply(new Rational(0, 1)); + Rational actual = new Rational(1, 2) + .multiply(new Rational(0, 1)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Divide two positive rational numbers") - public void testDivideTwoPositiveRationalNumbers() { + @DisplayName("Arithmetic -> Division -> Divide two positive rational numbers") + public void arithmeticDivisionDivideTwoPositiveRationalNumbers() { Rational expected = new Rational(3, 4); - Rational actual = new Rational(1, 2).divide(new Rational(2, 3)); + Rational actual = new Rational(1, 2) + .divide(new Rational(2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Divide a positive rational number by a negative rational number") - public void testDivideAPositiveRationalNumberByANegativeRationalNumber() { + @DisplayName("Arithmetic -> Division -> Divide a positive rational number by a " + + "negative rational number") + public void arithmeticDivisionDivideAPositiveRationalNumberByANegativeRationa() { Rational expected = new Rational(-3, 4); - Rational actual = new Rational(1, 2).divide(new Rational(-2, 3)); + Rational actual = new Rational(1, 2) + .divide(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Divide two negative rational numbers") - public void testDivideTwoNegativeRationalNumbers() { + @DisplayName("Arithmetic -> Division -> Divide two negative rational numbers") + public void arithmeticDivisionDivideTwoNegativeRationalNumbers() { Rational expected = new Rational(3, 4); - Rational actual = new Rational(-1, 2).divide(new Rational(-2, 3)); + Rational actual = new Rational(-1, 2) + .divide(new Rational(-2, 3)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Divide a rational number by 1") - public void testDivideARationalNumberByOne() { + @DisplayName("Arithmetic -> Division -> Divide a rational number by 1") + public void arithmeticDivisionDivideARationalNumberBy1() { Rational expected = new Rational(1, 2); - Rational actual = new Rational(1, 2).divide(new Rational(1, 1)); + Rational actual = new Rational(1, 2) + .divide(new Rational(1, 1)); assertThat(actual).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a positive rational number") - public void testAbsoluteValueOfAPositiveRationalNumber() { + @DisplayName("Absolute value -> Absolute value of a positive rational number") + public void absoluteValueAbsoluteValueOfAPositiveRationalNumber() { Rational expected = new Rational(1, 2); Rational actual = new Rational(1, 2).abs(); assertThat(actual).isEqualTo(expected); @@ -189,8 +207,9 @@ public void testAbsoluteValueOfAPositiveRationalNumber() { @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a positive rational number with negative numerator and denominator") - public void testAbsoluteValueOfAPositiveRationalNumberWithNegativeNumeratorAndDenominator() { + @DisplayName("Absolute value -> Absolute value of a positive rational number with " + + "negative numerator and denominator") + public void absoluteValueAbsoluteValueOfAPositiveRationalNumberWithNegativeNu() { Rational expected = new Rational(1, 2); Rational actual = new Rational(-1, -2).abs(); assertThat(actual).isEqualTo(expected); @@ -198,8 +217,8 @@ public void testAbsoluteValueOfAPositiveRationalNumberWithNegativeNumeratorAndDe @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a negative rational number") - public void testAbsoluteValueOfANegativeRationalNumber() { + @DisplayName("Absolute value -> Absolute value of a negative rational number") + public void absoluteValueAbsoluteValueOfANegativeRationalNumber() { Rational expected = new Rational(1, 2); Rational actual = new Rational(-1, 2).abs(); assertThat(actual).isEqualTo(expected); @@ -207,8 +226,9 @@ public void testAbsoluteValueOfANegativeRationalNumber() { @Disabled("Remove to run test") @Test - @DisplayName("\"Absolute value of a negative rational number with negative denominator") - public void testAbsoluteValueOfANegativeRationalNumberWithNegativeDenominator() { + @DisplayName("Absolute value -> Absolute value of a negative rational number with " + + "negative denominator") + public void absoluteValueAbsoluteValueOfANegativeRationalNumberWithNegativeDe() { Rational expected = new Rational(1, 2); Rational actual = new Rational(1, -2).abs(); assertThat(actual).isEqualTo(expected); @@ -216,17 +236,17 @@ public void testAbsoluteValueOfANegativeRationalNumberWithNegativeDenominator() @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of zero") - public void testAbsoluteValueOfZero() { + @DisplayName("Absolute value -> Absolute value of zero") + public void absoluteValueAbsoluteValueOfZero() { Rational expected = new Rational(0, 1); Rational actual = new Rational(0, 1).abs(); assertThat(actual).isEqualTo(expected); } - + @Disabled("Remove to run test") @Test - @DisplayName("Absolute value of a rational number is reduced to lowest terms") - public void testAbsoluteValueOfARationalNumberIsReducedToLowestTerms() { + @DisplayName("Absolute value -> Absolute value of a rational number is reduced to lowest terms") + public void absoluteValueAbsoluteValueOfARationalNumberIsReducedToLowestTerms() { Rational expected = new Rational(1, 2); Rational actual = new Rational(2, 4).abs(); assertThat(actual).isEqualTo(expected); @@ -234,8 +254,9 @@ public void testAbsoluteValueOfARationalNumberIsReducedToLowestTerms() { @Disabled("Remove to run test") @Test - @DisplayName("Raise a positive rational number to a positive integer power") - public void testRaiseAPositiveRationalNumberToAPositiveIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise a positive rational " + + "number to a positive integer power") + public void exponentiationOfARationalNumberRaiseAPositiveRationalNumberToAPos() { Rational expected = new Rational(1, 8); Rational actual = new Rational(1, 2).pow(3); assertThat(actual).isEqualTo(expected); @@ -243,35 +264,39 @@ public void testRaiseAPositiveRationalNumberToAPositiveIntegerPower() { @Disabled("Remove to run test") @Test - @DisplayName("Raise a negative rational number to a positive integer power") - public void testRaiseANegativeRationalNumberToAPositiveIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise a negative rational " + + "number to a positive integer power") + public void exponentiationOfARationalNumberRaiseANegativeRationalNumberToAPos() { Rational expected = new Rational(-1, 8); Rational actual = new Rational(-1, 2).pow(3); assertThat(actual).isEqualTo(expected); } - + @Disabled("Remove to run test") @Test - @DisplayName("Raise a positive rational number to a negative integer power") - public void testRaiseAPositiveRationalNumberToANegativeIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise a positive rational " + + "number to a negative integer power") + public void exponentiationOfARationalNumberRaiseAPositiveRationalNumberToANeg() { Rational expected = new Rational(25, 9); Rational actual = new Rational(3, 5).pow(-2); assertThat(actual).isEqualTo(expected); } - + @Disabled("Remove to run test") @Test - @DisplayName("\"Raise a negative rational number to an even negative integer power") - public void testRaiseANegativeRationalNumberToAnEvenNegativeIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise a negative rational " + + "number to an even negative integer power") + public void exponentiationOfARationalNumberRaiseANegativeRationalNumberToAnEv() { Rational expected = new Rational(25, 9); Rational actual = new Rational(-3, 5).pow(-2); assertThat(actual).isEqualTo(expected); } - + @Disabled("Remove to run test") @Test - @DisplayName("Raise a negative rational number to an odd negative integer power") - public void testRaiseANegativeRationalNumberToAnOddNegativeIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise a negative rational " + + "number to an odd negative integer power") + public void exponentiationOfARationalNumberRaiseANegativeRationalNumberToAnOd() { Rational expected = new Rational(-125, 27); Rational actual = new Rational(-3, 5).pow(-3); assertThat(actual).isEqualTo(expected); @@ -279,8 +304,8 @@ public void testRaiseANegativeRationalNumberToAnOddNegativeIntegerPower() { @Disabled("Remove to run test") @Test - @DisplayName("Raise zero to an integer power") - public void testRaiseZeroToAnIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise zero to an integer power") + public void exponentiationOfARationalNumberRaiseZeroToAnIntegerPower() { Rational expected = new Rational(0, 1); Rational actual = new Rational(0, 1).pow(5); assertThat(actual).isEqualTo(expected); @@ -288,8 +313,8 @@ public void testRaiseZeroToAnIntegerPower() { @Disabled("Remove to run test") @Test - @DisplayName("Raise one to an integer power") - public void testRaiseOneToAnIntegerPower() { + @DisplayName("Exponentiation of a rational number -> Raise one to an integer power") + public void exponentiationOfARationalNumberRaiseOneToAnIntegerPower() { Rational expected = new Rational(1, 1); Rational actual = new Rational(1, 1).pow(4); assertThat(actual).isEqualTo(expected); @@ -297,8 +322,19 @@ public void testRaiseOneToAnIntegerPower() { @Disabled("Remove to run test") @Test - @DisplayName("Raise a positive rational number to the power of zero") - public void testRaiseAPositiveRationalNumberToThePowerOfZero() { + @DisplayName("Exponentiation of a rational number -> Raise a positive rational " + + "number to the power of zero") + public void exponentiationOfARationalNumberRaiseAPositiveRationalNumberToTheP() { + Rational expected = new Rational(1, 1); + Rational actual = new Rational(1, 2).pow(0); + assertThat(actual).isEqualTo(expected); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Exponentiation of a rational number -> Raise a negative rational " + + "number to the power of zero") + public void exponentiationOfARationalNumberRaiseANegativeRationalNumberToTheP() { Rational expected = new Rational(1, 1); Rational actual = new Rational(-1, 2).pow(0); assertThat(actual).isEqualTo(expected); @@ -306,8 +342,9 @@ public void testRaiseAPositiveRationalNumberToThePowerOfZero() { @Disabled("Remove to run test") @Test - @DisplayName("Raise a real number to a positive rational number") - public void testRaiseARealNumberToAPositiveRationalNumber() { + @DisplayName("Exponentiation of a real number to a rational number -> Raise a real " + + "number to a positive rational number") + public void exponentiationOfARealNumberToARationalNumberRaiseARealNumberToAPo() { double expected = 16.0; double actual = new Rational(4, 3).exp(8.0); assertDoublesEqual(expected, actual); @@ -315,26 +352,37 @@ public void testRaiseARealNumberToAPositiveRationalNumber() { @Disabled("Remove to run test") @Test - @DisplayName("Raise a real number to a negative rational number") - public void testRaiseARealNumberToANegativeRationalNumber() { + @DisplayName("Exponentiation of a real number to a rational number -> Raise a real " + + "number to a negative rational number") + public void exponentiationOfARealNumberToARationalNumberRaiseARealNumberToANe() { double expected = 1.0 / 3; - double actual = new Rational(-1, 2).exp(9); + double actual = new Rational(-1, 2).exp(9.0); assertDoublesEqual(expected, actual); } @Disabled("Remove to run test") @Test - @DisplayName("Reduce a positive rational number to lowest terms") - public void testReduceAPositiveRationalNumberToLowestTerms() { + @DisplayName("Exponentiation of a real number to a rational number -> Raise a real " + + "number to a zero rational number") + public void exponentiationOfARealNumberToARationalNumberRaiseARealNumberToAZe() { + double expected = 1.0; + double actual = new Rational(0, 1).exp(2.0); + assertDoublesEqual(expected, actual); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Reduction to lowest terms -> Reduce a positive rational number to lowest terms") + public void reductionToLowestTermsReduceAPositiveRationalNumberToLowestTerms() { Rational expected = new Rational(1, 2); Rational actual = new Rational(2, 4); assertThat(actual).isEqualTo(expected); } - + @Disabled("Remove to run test") @Test - @DisplayName("Reduce places the minus sign on the numerator") - public void testReducePlacesTheMinusSignOnTheNumerator() { + @DisplayName("Reduction to lowest terms -> Reduce places the minus sign on the numerator") + public void reductionToLowestTermsReducePlacesTheMinusSignOnTheNumerator() { Rational expected = new Rational(-3, 4); Rational actual = new Rational(3, -4); assertThat(actual).isEqualTo(expected); @@ -342,8 +390,8 @@ public void testReducePlacesTheMinusSignOnTheNumerator() { @Disabled("Remove to run test") @Test - @DisplayName("Reduce a negative rational number to lowest terms") - public void testReduceANegativeRationalNumberToLowestTerms() { + @DisplayName("Reduction to lowest terms -> Reduce a negative rational number to lowest terms") + public void reductionToLowestTermsReduceANegativeRationalNumberToLowestTerms() { Rational expected = new Rational(-2, 3); Rational actual = new Rational(-4, 6); assertThat(actual).isEqualTo(expected); @@ -351,8 +399,9 @@ public void testReduceANegativeRationalNumberToLowestTerms() { @Disabled("Remove to run test") @Test - @DisplayName("Reduce a rational number with a negative denominator to lowest terms") - public void testReduceARationalNumberWithANegativeDenominatorToLowestTerms() { + @DisplayName("Reduction to lowest terms -> Reduce a rational number with a negative " + + "denominator to lowest terms") + public void reductionToLowestTermsReduceARationalNumberWithANegativeDenominat() { Rational expected = new Rational(-1, 3); Rational actual = new Rational(3, -9); assertThat(actual).isEqualTo(expected); @@ -360,8 +409,8 @@ public void testReduceARationalNumberWithANegativeDenominatorToLowestTerms() { @Disabled("Remove to run test") @Test - @DisplayName("Reduce zero to lowest terms") - public void testReduceZeroToLowestTerms() { + @DisplayName("Reduction to lowest terms -> Reduce zero to lowest terms") + public void reductionToLowestTermsReduceZeroToLowestTerms() { Rational expected = new Rational(0, 1); Rational actual = new Rational(0, 6); assertThat(actual).isEqualTo(expected); @@ -369,8 +418,8 @@ public void testReduceZeroToLowestTerms() { @Disabled("Remove to run test") @Test - @DisplayName("Reduce an integer to lowest terms") - public void testReduceAnIntegerToLowestTerms() { + @DisplayName("Reduction to lowest terms -> Reduce an integer to lowest terms") + public void reductionToLowestTermsReduceAnIntegerToLowestTerms() { Rational expected = new Rational(-2, 1); Rational actual = new Rational(-14, 7); assertThat(actual).isEqualTo(expected); @@ -378,10 +427,11 @@ public void testReduceAnIntegerToLowestTerms() { @Disabled("Remove to run test") @Test - @DisplayName("Reduce one to lowest terms") - public void testReduceOneToLowestTerms() { + @DisplayName("Reduction to lowest terms -> Reduce one to lowest terms") + public void reductionToLowestTermsReduceOneToLowestTerms() { Rational expected = new Rational(1, 1); Rational actual = new Rational(13, 13); assertThat(actual).isEqualTo(expected); } + } diff --git a/exercises/practice/react/src/test/java/ReactTest.java b/exercises/practice/react/src/test/java/ReactTest.java index e7c18a063..cf42a7892 100644 --- a/exercises/practice/react/src/test/java/ReactTest.java +++ b/exercises/practice/react/src/test/java/ReactTest.java @@ -12,58 +12,60 @@ public class ReactTest { @Test @DisplayName("input cells have a value") - public void testInputCellHasValue() { + public void inputCellsHaveAValue() { var input = React.inputCell(10); assertThat(input.getValue()).isEqualTo(10); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("an input cell's value can be set") - public void testInputCellValueCanBeSet() { + public void anInputCellSValueCanBeSet() { var input = React.inputCell(4); + input.setValue(20); assertThat(input.getValue()).isEqualTo(20); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("compute cells calculate initial value") - public void testComputeCellCalculateInitialValue() { + public void computeCellsCalculateInitialValue() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); assertThat(output.getValue()).isEqualTo(2); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("compute cells take inputs in the right order") - public void testComputeCellsInTheRightOrder() { - var first = React.inputCell(1); - var second = React.inputCell(2); - var output = React.computeCell(list -> list.get(0) + list.get(1) * 10, List.of(first, second)); + public void computeCellsTakeInputsInTheRightOrder() { + var one = React.inputCell(1); + var two = React.inputCell(2); + var output = React.computeCell(list -> list.get(0) + list.get(1) * 10, List.of(one, two)); assertThat(output.getValue()).isEqualTo(21); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("compute cells update value when dependencies are changed") - public void testComputeCellsUpdateValueWhenDependenciesAreChanged() { + public void computeCellsUpdateValueWhenDependenciesAreChanged() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); input.setValue(3); + assertThat(output.getValue()).isEqualTo(4); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("compute cells can depend on other compute cells") - public void testComputeCellsCanDependOnOtherComputeCells() { + public void computeCellsCanDependOnOtherComputeCells() { var input = React.inputCell(1); var timesTwo = React.computeCell(list -> list.get(0) * 2, List.of(input)); var timesThirty = React.computeCell(list -> list.get(0) * 30, List.of(input)); @@ -72,13 +74,14 @@ public void testComputeCellsCanDependOnOtherComputeCells() { assertThat(output.getValue()).isEqualTo(32); input.setValue(3); + assertThat(output.getValue()).isEqualTo(96); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("compute cells fire callbacks") - public void testComputeCellsFireCallbacks() { + public void computeCellsFireCallbacks() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); @@ -89,10 +92,10 @@ public void testComputeCellsFireCallbacks() { assertThat(values).containsExactly(4); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callback cells only fire on change") - public void testCallbacksOnlyFireOnChange() { + public void callbackCellsOnlyFireOnChange() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) < 3 ? 111 : 222, List.of(input)); @@ -106,10 +109,10 @@ public void testCallbacksOnlyFireOnChange() { assertThat(values).containsExactly(222); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callbacks do not report already reported values") - public void testCallbacksDoNotReportAlreadyReportedValues() { + public void callbacksDoNotReportAlreadyReportedValues() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); @@ -124,10 +127,10 @@ public void testCallbacksDoNotReportAlreadyReportedValues() { assertThat(values).containsExactly(4); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callbacks can fire from multiple cells") - public void testCallbacksCanFireFromMultipleCells() { + public void callbacksCanFireFromMultipleCells() { var input = React.inputCell(1); var plusOne = React.computeCell(list -> list.get(0) + 1, List.of(input)); var minusOne = React.computeCell(list -> list.get(0) - 1, List.of(input)); @@ -143,10 +146,10 @@ public void testCallbacksCanFireFromMultipleCells() { assertThat(values2).containsExactly(9); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callbacks can be added and removed") - public void testCallbacksCanBeAddedAndRemoved() { + public void callbacksCanBeAddedAndRemoved() { var input = React.inputCell(11); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); @@ -160,7 +163,6 @@ public void testCallbacksCanBeAddedAndRemoved() { input.setValue(31); assertThat(values1).containsExactly(32); assertThat(values2).containsExactly(32); - values1.clear(); values2.clear(); @@ -170,16 +172,15 @@ public void testCallbacksCanBeAddedAndRemoved() { output.addCallback(values3::add); input.setValue(41); - - assertThat(values1).isEmpty(); assertThat(values2).containsExactly(42); assertThat(values3).containsExactly(42); + assertThat(values1).isEmpty(); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("removing a callback multiple times doesn't interfere with other callbacks") - public void testRemovingACallbackMultipleTimesDoesntInterfereWithOtherCallbacks() { + public void removingACallbackMultipleTimesDoesnTInterfereWithOtherCallbacks() { var input = React.inputCell(1); var output = React.computeCell(list -> list.get(0) + 1, List.of(input)); @@ -188,22 +189,23 @@ public void testRemovingACallbackMultipleTimesDoesntInterfereWithOtherCallbacks( output.addCallback(callback1); var values2 = new ArrayList(); - Consumer callback2 = values2::add; - output.addCallback(callback2); + output.addCallback(values2::add); + + output.removeCallback(callback1); output.removeCallback(callback1); + output.removeCallback(callback1); input.setValue(2); assertThat(values2).containsExactly(3); - assertThat(values1).isEmpty(); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callbacks should only be called once even if multiple dependencies change") - public void testCallbacksShouldOnlyBeCalledOnceEvenIfMultipleDependenciesChange() { + public void callbacksShouldOnlyBeCalledOnceEvenIfMultipleDependenciesChange() { var input = React.inputCell(1); var plusOne = React.computeCell(list -> list.get(0) + 1, List.of(input)); var minusOne1 = React.computeCell(list -> list.get(0) - 1, List.of(input)); @@ -217,10 +219,10 @@ public void testCallbacksShouldOnlyBeCalledOnceEvenIfMultipleDependenciesChange( assertThat(values).containsExactly(10); } - @Disabled("Remove to run") + @Disabled("Remove to run test") @Test @DisplayName("callbacks should not be called if dependencies change but output value doesn't change") - public void testCallbacksShouldNotBeCalledIfDependenciesChangeButOutputValueDoesntChange() { + public void callbacksShouldNotBeCalledIfDependenciesChangeButOutputValueDoesn() { var input = React.inputCell(1); var plusOne = React.computeCell(list -> list.get(0) + 1, List.of(input)); var minusOne = React.computeCell(list -> list.get(0) - 1, List.of(input)); @@ -241,4 +243,5 @@ public void testCallbacksShouldNotBeCalledIfDependenciesChangeButOutputValueDoes input.setValue(5); assertThat(values).isEmpty(); } + } diff --git a/exercises/practice/rectangles/src/test/java/RectangleCounterTest.java b/exercises/practice/rectangles/src/test/java/RectangleCounterTest.java index c1f665729..d4e923f28 100644 --- a/exercises/practice/rectangles/src/test/java/RectangleCounterTest.java +++ b/exercises/practice/rectangles/src/test/java/RectangleCounterTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,169 +6,165 @@ public class RectangleCounterTest { - private RectangleCounter rectangleCounter; - - @BeforeEach - public void setUp() { - rectangleCounter = new RectangleCounter(); - } - @Test @DisplayName("no rows") - public void testInputWithNoRowsContainsNoRectangles() { - String[] inputGrid = new String[]{}; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(0); + public void noRows() { + assertThat(new RectangleCounter().countRectangles(new String[]{})) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("no columns") - public void testInputWithNoColumnsContainsNoRectangles() { - String[] inputGrid = new String[]{""}; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(0); + public void noColumns() { + String[] grid = new String[]{ + "" + }; + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("no rectangles") - public void testNonTrivialInputWithNoRectangles() { - String[] inputGrid = new String[]{" "}; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(0); + public void noRectangles() { + String[] grid = new String[]{ + " " + }; + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("one rectangle") - public void testInputWithOneRectangle() { - String[] inputGrid = new String[]{ + public void oneRectangle() { + String[] grid = new String[]{ "+-+", "| |", "+-+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(1); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("two rectangles without shared parts") - public void testInputWithTwoRectanglesWithoutSharedEdges() { - String[] inputGrid = new String[]{ + public void twoRectanglesWithoutSharedParts() { + String[] grid = new String[]{ " +-+", " | |", "+-+-+", "| | ", "+-+ " }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(2); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("five rectangles with shared parts") - public void testInputWithFiveRectanglesWithSharedEdges() { - String[] inputGrid = new String[]{ + public void fiveRectanglesWithSharedParts() { + String[] grid = new String[]{ " +-+", " | |", "+-+-+", "| | |", "+-+-+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(5); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(5); } @Disabled("Remove to run test") @Test @DisplayName("rectangle of height 1 is counted") - public void testThatRectangleOfHeightOneIsCounted() { - String[] inputGrid = new String[]{ + public void rectangleOfHeight1IsCounted() { + String[] grid = new String[]{ "+--+", "+--+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(1); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("rectangle of width 1 is counted") - public void testThatRectangleOfWidthOneIsCounted() { - String[] inputGrid = new String[]{ + public void rectangleOfWidth1IsCounted() { + String[] grid = new String[]{ "++", "||", "++" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(1); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("1x1 square is counted") - public void testThatOneByOneSquareIsCounted() { - String[] inputGrid = new String[]{ + public void test1x1SquareIsCounted() { + String[] grid = new String[]{ "++", "++" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(1); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("only complete rectangles are counted") - public void testThatIncompleteRectanglesAreNotCounted() { - String[] inputGrid = new String[]{ + public void onlyCompleteRectanglesAreCounted() { + String[] grid = new String[]{ " +-+", " |", "+-+-+", "| | -", "+-+-+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(1); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("rectangles can be of different sizes") - public void testThatRectanglesOfDifferentSizesAreAllCounted() { - String[] inputGrid = new String[]{ + public void rectanglesCanBeOfDifferentSizes() { + String[] grid = new String[]{ "+------+----+", "| | |", "+---+--+ |", "| | |", "+---+-------+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(3); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("corner is required for a rectangle to be complete") - public void testThatIntersectionsWithoutCornerCharacterDoNotCountAsRectangleCorners() { - String[] inputGrid = new String[]{ + public void cornerIsRequiredForARectangleToBeComplete() { + String[] grid = new String[]{ "+------+----+", "| | |", "+------+ |", "| | |", "+---+-------+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(2); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("large input with many rectangles") - public void testLargeInputWithManyRectangles() { - String[] inputGrid = new String[]{ + public void largeInputWithManyRectangles() { + String[] grid = new String[]{ "+---+--+----+", "| +--+----+", "+---+--+ |", @@ -179,15 +174,15 @@ public void testLargeInputWithManyRectangles() { "+------+ | |", " +-+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(60); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(60); } - + @Disabled("Remove to run test") @Test @DisplayName("rectangles must have four sides") - public void testRectanglesMustHaveFourSides() { - String[] inputGrid = new String[]{ + public void rectanglesMustHaveFourSides() { + String[] grid = new String[]{ "+-+ +-+", "| | | |", "+-+-+-+", @@ -196,7 +191,8 @@ public void testRectanglesMustHaveFourSides() { "| | | |", "+-+ +-+" }; - - assertThat(rectangleCounter.countRectangles(inputGrid)).isEqualTo(5); + assertThat(new RectangleCounter().countRectangles(grid)) + .isEqualTo(5); } + } diff --git a/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java b/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java index b10a9459f..a22029a9d 100644 --- a/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java +++ b/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java @@ -2,266 +2,260 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; - -import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; - public class RelativeDistanceTest { @Test @DisplayName("Direct parent-child relation") - public void testDirectParentChildRelation() { - Map> familyTree = new HashMap<>() { - { - put("Vera", List.of("Tomoko")); - put("Tomoko", List.of("Aditi")); - } - }; - + public void directParentChildRelation() { + Map> familyTree = Map.of("Vera", List.of("Tomoko"), "Tomoko", List.of("Aditi")); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Vera", "Tomoko")).isEqualTo(1); + + assertThat(rd.degreeOfSeparation("Vera", "Tomoko")) + + .isEqualTo(1); + } @Disabled("Remove to run test") @Test @DisplayName("Sibling relationship") - public void testSiblingRelationship() { - Map> familyTree = new HashMap<>() { - { - put("Dalia", List.of("Olga", "Yassin")); - } - }; - + public void siblingRelationship() { + Map> familyTree = Map.of("Dalia", List.of("Olga", "Yassin")); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Olga", "Yassin")).isEqualTo(1); + + assertThat(rd.degreeOfSeparation("Olga", "Yassin")) + + .isEqualTo(1); + } @Disabled("Remove to run test") @Test @DisplayName("Two degrees of separation, grandchild") - public void testTwoDegreesOfSeparationGrandchild() { - Map> familyTree = new HashMap<>() { - { - put("Khadija", List.of("Mateo")); - put("Mateo", List.of("Rami")); - } - }; - + public void twoDegreesOfSeparationGrandchild() { + Map> familyTree = Map.of("Khadija", List.of("Mateo"), "Mateo", List.of("Rami")); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Khadija", "Rami")).isEqualTo(2); + + assertThat(rd.degreeOfSeparation("Khadija", "Rami")) + + .isEqualTo(2); + } @Disabled("Remove to run test") @Test @DisplayName("Unrelated individuals") - public void testUnrelatedIndividuals() { - Map> familyTree = new HashMap<>() { - { - put("Priya", List.of("Rami")); - put("Kaito", List.of("Elif")); - } - }; - + public void unrelatedIndividuals() { + Map> familyTree = Map.of("Priya", List.of("Rami"), "Kaito", List.of("Elif")); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Priya", "Kaito")).isEqualTo(-1); + + assertThat(rd.degreeOfSeparation("Priya", "Kaito")) + + .isEqualTo(-1); + } @Disabled("Remove to run test") @Test @DisplayName("Complex graph, cousins") - public void testComplexGraphCousins() { - Map> familyTree = new HashMap<>() { - { - put("Aiko", List.of("Bao", "Carlos")); - put("Bao", List.of("Dalia", "Elias")); - put("Carlos", List.of("Fatima", "Gustavo")); - put("Dalia", List.of("Hassan", "Isla")); - put("Elias", List.of("Javier")); - put("Fatima", List.of("Khadija", "Liam")); - put("Gustavo", List.of("Mina")); - put("Hassan", List.of("Noah", "Olga")); - put("Isla", List.of("Pedro")); - put("Javier", List.of("Quynh", "Ravi")); - put("Khadija", List.of("Sofia")); - put("Liam", List.of("Tariq", "Uma")); - put("Mina", List.of("Viktor", "Wang")); - put("Noah", List.of("Xiomara")); - put("Olga", List.of("Yuki")); - put("Pedro", List.of("Zane", "Aditi")); - put("Quynh", List.of("Boris")); - put("Ravi", List.of("Celine")); - put("Sofia", List.of("Diego", "Elif")); - put("Tariq", List.of("Farah")); - put("Uma", List.of("Giorgio")); - put("Viktor", List.of("Hana", "Ian")); - put("Wang", List.of("Jing")); - put("Xiomara", List.of("Kaito")); - put("Yuki", List.of("Leila")); - put("Zane", List.of("Mateo")); - put("Aditi", List.of("Nia")); - put("Boris", List.of("Oscar")); - put("Celine", List.of("Priya")); - put("Diego", List.of("Qi")); - put("Elif", List.of("Rami")); - put("Farah", List.of("Sven")); - put("Giorgio", List.of("Tomoko")); - put("Hana", List.of("Umar")); - put("Ian", List.of("Vera")); - put("Jing", List.of("Wyatt")); - put("Kaito", List.of("Xia")); - put("Leila", List.of("Yassin")); - put("Mateo", List.of("Zara")); - put("Nia", List.of("Antonio")); - put("Oscar", List.of("Bianca")); - put("Priya", List.of("Cai")); - put("Qi", List.of("Dimitri")); - put("Rami", List.of("Ewa")); - put("Sven", List.of("Fabio")); - put("Tomoko", List.of("Gabriela")); - put("Umar", List.of("Helena")); - put("Vera", List.of("Igor")); - put("Wyatt", List.of("Jun")); - put("Xia", List.of("Kim")); - put("Yassin", List.of("Lucia")); - put("Zara", List.of("Mohammed")); - } - }; - + public void complexGraphCousins() { + Map> familyTree = Map.ofEntries( + Map.entry("Aiko", List.of("Bao", "Carlos")), + Map.entry("Bao", List.of("Dalia", "Elias")), + Map.entry("Carlos", List.of("Fatima", "Gustavo")), + Map.entry("Dalia", List.of("Hassan", "Isla")), + Map.entry("Elias", List.of("Javier")), + Map.entry("Fatima", List.of("Khadija", "Liam")), + Map.entry("Gustavo", List.of("Mina")), + Map.entry("Hassan", List.of("Noah", "Olga")), + Map.entry("Isla", List.of("Pedro")), + Map.entry("Javier", List.of("Quynh", "Ravi")), + Map.entry("Khadija", List.of("Sofia")), + Map.entry("Liam", List.of("Tariq", "Uma")), + Map.entry("Mina", List.of("Viktor", "Wang")), + Map.entry("Noah", List.of("Xiomara")), + Map.entry("Olga", List.of("Yuki")), + Map.entry("Pedro", List.of("Zane", "Aditi")), + Map.entry("Quynh", List.of("Boris")), + Map.entry("Ravi", List.of("Celine")), + Map.entry("Sofia", List.of("Diego", "Elif")), + Map.entry("Tariq", List.of("Farah")), + Map.entry("Uma", List.of("Giorgio")), + Map.entry("Viktor", List.of("Hana", "Ian")), + Map.entry("Wang", List.of("Jing")), + Map.entry("Xiomara", List.of("Kaito")), + Map.entry("Yuki", List.of("Leila")), + Map.entry("Zane", List.of("Mateo")), + Map.entry("Aditi", List.of("Nia")), + Map.entry("Boris", List.of("Oscar")), + Map.entry("Celine", List.of("Priya")), + Map.entry("Diego", List.of("Qi")), + Map.entry("Elif", List.of("Rami")), + Map.entry("Farah", List.of("Sven")), + Map.entry("Giorgio", List.of("Tomoko")), + Map.entry("Hana", List.of("Umar")), + Map.entry("Ian", List.of("Vera")), + Map.entry("Jing", List.of("Wyatt")), + Map.entry("Kaito", List.of("Xia")), + Map.entry("Leila", List.of("Yassin")), + Map.entry("Mateo", List.of("Zara")), + Map.entry("Nia", List.of("Antonio")), + Map.entry("Oscar", List.of("Bianca")), + Map.entry("Priya", List.of("Cai")), + Map.entry("Qi", List.of("Dimitri")), + Map.entry("Rami", List.of("Ewa")), + Map.entry("Sven", List.of("Fabio")), + Map.entry("Tomoko", List.of("Gabriela")), + Map.entry("Umar", List.of("Helena")), + Map.entry("Vera", List.of("Igor")), + Map.entry("Wyatt", List.of("Jun")), + Map.entry("Xia", List.of("Kim")), + Map.entry("Yassin", List.of("Lucia")), + Map.entry("Zara", List.of("Mohammed")) + ); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Dimitri", "Fabio")).isEqualTo(9); + + assertThat(rd.degreeOfSeparation("Dimitri", "Fabio")) + + .isEqualTo(9); + } @Disabled("Remove to run test") @Test @DisplayName("Complex graph, no shortcut, far removed nephew") - public void testComplexGraphNoShortcutFarRemovedNephew() { - Map> familyTree = new HashMap<>() { - { - put("Aiko", List.of("Bao", "Carlos")); - put("Bao", List.of("Dalia", "Elias")); - put("Carlos", List.of("Fatima", "Gustavo")); - put("Dalia", List.of("Hassan", "Isla")); - put("Elias", List.of("Javier")); - put("Fatima", List.of("Khadija", "Liam")); - put("Gustavo", List.of("Mina")); - put("Hassan", List.of("Noah", "Olga")); - put("Isla", List.of("Pedro")); - put("Javier", List.of("Quynh", "Ravi")); - put("Khadija", List.of("Sofia")); - put("Liam", List.of("Tariq", "Uma")); - put("Mina", List.of("Viktor", "Wang")); - put("Noah", List.of("Xiomara")); - put("Olga", List.of("Yuki")); - put("Pedro", List.of("Zane", "Aditi")); - put("Quynh", List.of("Boris")); - put("Ravi", List.of("Celine")); - put("Sofia", List.of("Diego", "Elif")); - put("Tariq", List.of("Farah")); - put("Uma", List.of("Giorgio")); - put("Viktor", List.of("Hana", "Ian")); - put("Wang", List.of("Jing")); - put("Xiomara", List.of("Kaito")); - put("Yuki", List.of("Leila")); - put("Zane", List.of("Mateo")); - put("Aditi", List.of("Nia")); - put("Boris", List.of("Oscar")); - put("Celine", List.of("Priya")); - put("Diego", List.of("Qi")); - put("Elif", List.of("Rami")); - put("Farah", List.of("Sven")); - put("Giorgio", List.of("Tomoko")); - put("Hana", List.of("Umar")); - put("Ian", List.of("Vera")); - put("Jing", List.of("Wyatt")); - put("Kaito", List.of("Xia")); - put("Leila", List.of("Yassin")); - put("Mateo", List.of("Zara")); - put("Nia", List.of("Antonio")); - put("Oscar", List.of("Bianca")); - put("Priya", List.of("Cai")); - put("Qi", List.of("Dimitri")); - put("Rami", List.of("Ewa")); - put("Sven", List.of("Fabio")); - put("Tomoko", List.of("Gabriela")); - put("Umar", List.of("Helena")); - put("Vera", List.of("Igor")); - put("Wyatt", List.of("Jun")); - put("Xia", List.of("Kim")); - put("Yassin", List.of("Lucia")); - put("Zara", List.of("Mohammed")); - } - }; + public void complexGraphNoShortcutFarRemovedNephew() { + Map> familyTree = Map.ofEntries( + Map.entry("Aiko", List.of("Bao", "Carlos")), + Map.entry("Bao", List.of("Dalia", "Elias")), + Map.entry("Carlos", List.of("Fatima", "Gustavo")), + Map.entry("Dalia", List.of("Hassan", "Isla")), + Map.entry("Elias", List.of("Javier")), + Map.entry("Fatima", List.of("Khadija", "Liam")), + Map.entry("Gustavo", List.of("Mina")), + Map.entry("Hassan", List.of("Noah", "Olga")), + Map.entry("Isla", List.of("Pedro")), + Map.entry("Javier", List.of("Quynh", "Ravi")), + Map.entry("Khadija", List.of("Sofia")), + Map.entry("Liam", List.of("Tariq", "Uma")), + Map.entry("Mina", List.of("Viktor", "Wang")), + Map.entry("Noah", List.of("Xiomara")), + Map.entry("Olga", List.of("Yuki")), + Map.entry("Pedro", List.of("Zane", "Aditi")), + Map.entry("Quynh", List.of("Boris")), + Map.entry("Ravi", List.of("Celine")), + Map.entry("Sofia", List.of("Diego", "Elif")), + Map.entry("Tariq", List.of("Farah")), + Map.entry("Uma", List.of("Giorgio")), + Map.entry("Viktor", List.of("Hana", "Ian")), + Map.entry("Wang", List.of("Jing")), + Map.entry("Xiomara", List.of("Kaito")), + Map.entry("Yuki", List.of("Leila")), + Map.entry("Zane", List.of("Mateo")), + Map.entry("Aditi", List.of("Nia")), + Map.entry("Boris", List.of("Oscar")), + Map.entry("Celine", List.of("Priya")), + Map.entry("Diego", List.of("Qi")), + Map.entry("Elif", List.of("Rami")), + Map.entry("Farah", List.of("Sven")), + Map.entry("Giorgio", List.of("Tomoko")), + Map.entry("Hana", List.of("Umar")), + Map.entry("Ian", List.of("Vera")), + Map.entry("Jing", List.of("Wyatt")), + Map.entry("Kaito", List.of("Xia")), + Map.entry("Leila", List.of("Yassin")), + Map.entry("Mateo", List.of("Zara")), + Map.entry("Nia", List.of("Antonio")), + Map.entry("Oscar", List.of("Bianca")), + Map.entry("Priya", List.of("Cai")), + Map.entry("Qi", List.of("Dimitri")), + Map.entry("Rami", List.of("Ewa")), + Map.entry("Sven", List.of("Fabio")), + Map.entry("Tomoko", List.of("Gabriela")), + Map.entry("Umar", List.of("Helena")), + Map.entry("Vera", List.of("Igor")), + Map.entry("Wyatt", List.of("Jun")), + Map.entry("Xia", List.of("Kim")), + Map.entry("Yassin", List.of("Lucia")), + Map.entry("Zara", List.of("Mohammed")) + ); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Lucia", "Jun")).isEqualTo(14); + + assertThat(rd.degreeOfSeparation("Lucia", "Jun")) + + .isEqualTo(14); + } @Disabled("Remove to run test") @Test - @DisplayName( - "Complex graph, some shortcuts, cross-down and cross-up, " + - "cousins several times removed, with unrelated family tree" - ) - public void testComplexGraphSomeShortcutsCrossDownAndCrossUpCousinsSeveralTimesRemovedWithUnrelatedFamilyTree() { - Map> familyTree = new HashMap<>() { - { - put("Aiko", List.of("Bao", "Carlos")); - put("Bao", List.of("Dalia")); - put("Carlos", List.of("Fatima", "Gustavo")); - put("Dalia", List.of("Hassan", "Isla")); - put("Fatima", List.of("Khadija", "Liam")); - put("Gustavo", List.of("Mina")); - put("Hassan", List.of("Noah", "Olga")); - put("Isla", List.of("Pedro")); - put("Javier", List.of("Quynh", "Ravi")); - put("Khadija", List.of("Sofia")); - put("Liam", List.of("Tariq", "Uma")); - put("Mina", List.of("Viktor", "Wang")); - put("Noah", List.of("Xiomara")); - put("Olga", List.of("Yuki")); - put("Pedro", List.of("Zane", "Aditi")); - put("Quynh", List.of("Boris")); - put("Ravi", List.of("Celine")); - put("Sofia", List.of("Diego", "Elif")); - put("Tariq", List.of("Farah")); - put("Uma", List.of("Giorgio")); - put("Viktor", List.of("Hana", "Ian")); - put("Wang", List.of("Jing")); - put("Xiomara", List.of("Kaito")); - put("Yuki", List.of("Leila")); - put("Zane", List.of("Mateo")); - put("Aditi", List.of("Nia")); - put("Boris", List.of("Oscar")); - put("Celine", List.of("Priya")); - put("Diego", List.of("Qi")); - put("Elif", List.of("Rami")); - put("Farah", List.of("Sven")); - put("Giorgio", List.of("Tomoko")); - put("Hana", List.of("Umar")); - put("Ian", List.of("Vera")); - put("Jing", List.of("Wyatt")); - put("Kaito", List.of("Xia")); - put("Leila", List.of("Yassin")); - put("Mateo", List.of("Zara")); - put("Nia", List.of("Antonio")); - put("Oscar", List.of("Bianca")); - put("Priya", List.of("Cai")); - put("Qi", List.of("Dimitri")); - put("Rami", List.of("Ewa")); - put("Sven", List.of("Fabio")); - put("Tomoko", List.of("Gabriela")); - put("Umar", List.of("Helena")); - put("Vera", List.of("Igor")); - put("Wyatt", List.of("Jun")); - put("Xia", List.of("Kim")); - put("Yassin", List.of("Lucia")); - put("Zara", List.of("Mohammed")); - } - }; + @DisplayName("Complex graph, some shortcuts, cross-down and cross-up, cousins " + + "several times removed, with unrelated family tree") + public void complexGraphSomeShortcutsCrossDownAndCrossUpCousinsSeveralTimesRe() { + Map> familyTree = Map.ofEntries( + Map.entry("Aiko", List.of("Bao", "Carlos")), + Map.entry("Bao", List.of("Dalia")), + Map.entry("Carlos", List.of("Fatima", "Gustavo")), + Map.entry("Dalia", List.of("Hassan", "Isla")), + Map.entry("Fatima", List.of("Khadija", "Liam")), + Map.entry("Gustavo", List.of("Mina")), + Map.entry("Hassan", List.of("Noah", "Olga")), + Map.entry("Isla", List.of("Pedro")), + Map.entry("Javier", List.of("Quynh", "Ravi")), + Map.entry("Khadija", List.of("Sofia")), + Map.entry("Liam", List.of("Tariq", "Uma")), + Map.entry("Mina", List.of("Viktor", "Wang")), + Map.entry("Noah", List.of("Xiomara")), + Map.entry("Olga", List.of("Yuki")), + Map.entry("Pedro", List.of("Zane", "Aditi")), + Map.entry("Quynh", List.of("Boris")), + Map.entry("Ravi", List.of("Celine")), + Map.entry("Sofia", List.of("Diego", "Elif")), + Map.entry("Tariq", List.of("Farah")), + Map.entry("Uma", List.of("Giorgio")), + Map.entry("Viktor", List.of("Hana", "Ian")), + Map.entry("Wang", List.of("Jing")), + Map.entry("Xiomara", List.of("Kaito")), + Map.entry("Yuki", List.of("Leila")), + Map.entry("Zane", List.of("Mateo")), + Map.entry("Aditi", List.of("Nia")), + Map.entry("Boris", List.of("Oscar")), + Map.entry("Celine", List.of("Priya")), + Map.entry("Diego", List.of("Qi")), + Map.entry("Elif", List.of("Rami")), + Map.entry("Farah", List.of("Sven")), + Map.entry("Giorgio", List.of("Tomoko")), + Map.entry("Hana", List.of("Umar")), + Map.entry("Ian", List.of("Vera")), + Map.entry("Jing", List.of("Wyatt")), + Map.entry("Kaito", List.of("Xia")), + Map.entry("Leila", List.of("Yassin")), + Map.entry("Mateo", List.of("Zara")), + Map.entry("Nia", List.of("Antonio")), + Map.entry("Oscar", List.of("Bianca")), + Map.entry("Priya", List.of("Cai")), + Map.entry("Qi", List.of("Dimitri")), + Map.entry("Rami", List.of("Ewa")), + Map.entry("Sven", List.of("Fabio")), + Map.entry("Tomoko", List.of("Gabriela")), + Map.entry("Umar", List.of("Helena")), + Map.entry("Vera", List.of("Igor")), + Map.entry("Wyatt", List.of("Jun")), + Map.entry("Xia", List.of("Kim")), + Map.entry("Yassin", List.of("Lucia")), + Map.entry("Zara", List.of("Mohammed")) + ); RelativeDistance rd = new RelativeDistance(familyTree); - assertThat(rd.degreeOfSeparation("Wyatt", "Xia")).isEqualTo(12); + + assertThat(rd.degreeOfSeparation("Wyatt", "Xia")) + + .isEqualTo(12); + } + } diff --git a/exercises/practice/resistor-color-duo/src/test/java/ResistorColorDuoTest.java b/exercises/practice/resistor-color-duo/src/test/java/ResistorColorDuoTest.java index 6e8c5d0d4..5b50db088 100644 --- a/exercises/practice/resistor-color-duo/src/test/java/ResistorColorDuoTest.java +++ b/exercises/practice/resistor-color-duo/src/test/java/ResistorColorDuoTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,72 +5,60 @@ import static org.assertj.core.api.Assertions.assertThat; public class ResistorColorDuoTest { - private ResistorColorDuo resistorColorDuo; - - @BeforeEach - public void setup() { - resistorColorDuo = new ResistorColorDuo(); - } @Test @DisplayName("Brown and black") - public void testBrownAndBlack() { - assertThat( - resistorColorDuo.value(new String[]{"brown", "black"}) - ).isEqualTo(10); + public void brownAndBlack() { + assertThat(new ResistorColorDuo().value(new String[]{"brown", "black"})) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Blue and grey") - public void testBlueAndGrey() { - assertThat( - resistorColorDuo.value(new String[]{ "blue", "grey" }) - ).isEqualTo(68); + public void blueAndGrey() { + assertThat(new ResistorColorDuo().value(new String[]{"blue", "grey"})) + .isEqualTo(68); } @Disabled("Remove to run test") @Test @DisplayName("Yellow and violet") - public void testYellowAndViolet() { - assertThat( - resistorColorDuo.value(new String[]{ "yellow", "violet" }) - ).isEqualTo(47); + public void yellowAndViolet() { + assertThat(new ResistorColorDuo().value(new String[]{"yellow", "violet"})) + .isEqualTo(47); } @Disabled("Remove to run test") @Test - @DisplayName("Orange and orange") - public void testOrangeAndOrange() { - assertThat( - resistorColorDuo.value(new String[]{ "orange", "orange" }) - ).isEqualTo(33); + @DisplayName("White and red") + public void whiteAndRed() { + assertThat(new ResistorColorDuo().value(new String[]{"white", "red"})) + .isEqualTo(92); } - + @Disabled("Remove to run test") @Test - @DisplayName("White and red") - public void testWhiteAndRed() { - assertThat( - resistorColorDuo.value(new String[]{ "white", "red" }) - ).isEqualTo(92); + @DisplayName("Orange and orange") + public void orangeAndOrange() { + assertThat(new ResistorColorDuo().value(new String[]{"orange", "orange"})) + .isEqualTo(33); } - + @Disabled("Remove to run test") @Test - @DisplayName("Black and brown, one-digit") - public void testBlackAndBrownOneDigit() { - assertThat( - resistorColorDuo.value(new String[]{ "black", "brown" }) - ).isEqualTo(1); + @DisplayName("Ignore additional colors") + public void ignoreAdditionalColors() { + assertThat(new ResistorColorDuo().value(new String[]{"green", "brown", "orange"})) + .isEqualTo(51); } @Disabled("Remove to run test") @Test - @DisplayName("Ignore additional colors") - public void testIgnoreAdditionalColors() { - assertThat( - resistorColorDuo.value(new String[]{ "green", "brown", "orange" }) - ).isEqualTo(51); + @DisplayName("Black and brown, one-digit") + public void blackAndBrownOneDigit() { + assertThat(new ResistorColorDuo().value(new String[]{"black", "brown"})) + .isEqualTo(1); } + } diff --git a/exercises/practice/resistor-color-trio/src/test/java/ResistorColorTrioTest.java b/exercises/practice/resistor-color-trio/src/test/java/ResistorColorTrioTest.java index 3c682c3be..ae0ab97a7 100644 --- a/exercises/practice/resistor-color-trio/src/test/java/ResistorColorTrioTest.java +++ b/exercises/practice/resistor-color-trio/src/test/java/ResistorColorTrioTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,99 +5,84 @@ import static org.assertj.core.api.Assertions.assertThat; public class ResistorColorTrioTest { - private ResistorColorTrio resistorColorTrio; - - @BeforeEach - public void setup() { - resistorColorTrio = new ResistorColorTrio(); - } @Test @DisplayName("Orange and orange and black") - public void testOrangeAndOrangeAndBlack() { - assertThat( - resistorColorTrio.label(new String[]{"orange", "orange", "black"}) - ).isEqualTo("33 ohms"); + public void orangeAndOrangeAndBlack() { + assertThat(new ResistorColorTrio().label(new String[]{"orange", "orange", "black"})) + .isEqualTo("33 ohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Blue and grey and brown") - public void testBlueAndGreyAndBrown() { - assertThat( - resistorColorTrio.label(new String[]{"blue", "grey", "brown"}) - ).isEqualTo("680 ohms"); + public void blueAndGreyAndBrown() { + assertThat(new ResistorColorTrio().label(new String[]{"blue", "grey", "brown"})) + .isEqualTo("680 ohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Red and black and red") - public void testRedAndBlackAndRed() { - assertThat( - resistorColorTrio.label(new String[]{"red", "black", "red"}) - ).isEqualTo("2 kiloohms"); + public void redAndBlackAndRed() { + assertThat(new ResistorColorTrio().label(new String[]{"red", "black", "red"})) + .isEqualTo("2 kiloohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Green and brown and orange") - public void testGreenAndBrownAndOrange() { - assertThat( - resistorColorTrio.label(new String[]{"green", "brown", "orange"}) - ).isEqualTo("51 kiloohms"); + public void greenAndBrownAndOrange() { + assertThat(new ResistorColorTrio().label(new String[]{"green", "brown", "orange"})) + .isEqualTo("51 kiloohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Yellow and violet and yellow") - public void testYellowAndVioletAndYellow() { - assertThat( - resistorColorTrio.label(new String[]{"yellow", "violet", "yellow"}) - ).isEqualTo("470 kiloohms"); + public void yellowAndVioletAndYellow() { + assertThat(new ResistorColorTrio().label(new String[]{"yellow", "violet", "yellow"})) + .isEqualTo("470 kiloohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Blue and violet and blue") - public void testBlueAndVioletAndBlue() { - assertThat( - resistorColorTrio.label(new String[]{"blue", "violet", "blue"}) - ).isEqualTo("67 megaohms"); + public void blueAndVioletAndBlue() { + assertThat(new ResistorColorTrio().label(new String[]{"blue", "violet", "blue"})) + .isEqualTo("67 megaohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("Minimum possible value") - public void testBlackAndBlackAndBlack() { - assertThat( - resistorColorTrio.label(new String[]{"black", "black", "black"}) - ).isEqualTo("0 ohms"); + public void minimumPossibleValue() { + assertThat(new ResistorColorTrio().label(new String[]{"black", "black", "black"})) + .isEqualTo("0 ohms"); } @Disabled("Remove to run test") @Test @DisplayName("Maximum possible value") - public void testWhiteAndWhiteAndWhite() { - assertThat( - resistorColorTrio.label(new String[]{"white", "white", "white"}) - ).isEqualTo("99 gigaohms"); + public void maximumPossibleValue() { + assertThat(new ResistorColorTrio().label(new String[]{"white", "white", "white"})) + .isEqualTo("99 gigaohms"); } - + @Disabled("Remove to run test") @Test @DisplayName("First two colors make an invalid octal number") - public void testFirstTwoColorsMakeAnInvalidOctalNumber() { - assertThat( - resistorColorTrio.label(new String[]{"black", "grey", "black"}) - ).isEqualTo("8 ohms"); + public void firstTwoColorsMakeAnInvalidOctalNumber() { + assertThat(new ResistorColorTrio().label(new String[]{"black", "grey", "black"})) + .isEqualTo("8 ohms"); } @Disabled("Remove to run test") @Test @DisplayName("Ignore extra colors") - public void testIgnoreExtraColors() { - assertThat( - resistorColorTrio.label(new String[]{"blue", "green", "yellow", "orange"}) - ).isEqualTo("650 kiloohms"); + public void ignoreExtraColors() { + assertThat(new ResistorColorTrio().label(new String[]{"blue", "green", "yellow", "orange"})) + .isEqualTo("650 kiloohms"); } + } diff --git a/exercises/practice/resistor-color/src/test/java/ResistorColorTest.java b/exercises/practice/resistor-color/src/test/java/ResistorColorTest.java index 9eb218d05..e0f214b08 100644 --- a/exercises/practice/resistor-color/src/test/java/ResistorColorTest.java +++ b/exercises/practice/resistor-color/src/test/java/ResistorColorTest.java @@ -1,44 +1,50 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; + import static org.assertj.core.api.Assertions.assertThat; public class ResistorColorTest { - private ResistorColor resistorColor; - - @BeforeEach - public void setup() { - resistorColor = new ResistorColor(); - } - @Test - @DisplayName("Black") - public void testBlackColorCode() { - assertThat(resistorColor.colorCode("black")).isEqualTo(0); + @DisplayName("Color codes -> Black") + public void colorCodesBlack() { + assertThat(new ResistorColor().colorCode("black")) + .isEqualTo(0); } @Disabled("Remove to run test") @Test - @DisplayName("white") - public void testWhiteColorCode() { - assertThat(resistorColor.colorCode("white")).isEqualTo(9); + @DisplayName("Color codes -> White") + public void colorCodesWhite() { + assertThat(new ResistorColor().colorCode("white")) + .isEqualTo(9); } @Disabled("Remove to run test") @Test - @DisplayName("Orange") - public void testOrangeColorCode() { - assertThat(resistorColor.colorCode("orange")).isEqualTo(3); + @DisplayName("Color codes -> Orange") + public void colorCodesOrange() { + assertThat(new ResistorColor().colorCode("orange")) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("Colors") - public void testColors() { - assertThat(resistorColor.colors()).containsExactly( - "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" - ); + public void colors() { + assertThat(new ResistorColor().colors()) + .containsExactly( + "black", + "brown", + "red", + "orange", + "yellow", + "green", + "blue", + "violet", + "grey", + "white"); } + } diff --git a/exercises/practice/rest-api/src/test/java/RestApiTest.java b/exercises/practice/rest-api/src/test/java/RestApiTest.java index e17d0a9a6..3b3b2f613 100644 --- a/exercises/practice/rest-api/src/test/java/RestApiTest.java +++ b/exercises/practice/rest-api/src/test/java/RestApiTest.java @@ -9,10 +9,11 @@ public class RestApiTest { @Test - @DisplayName("no users") - public void noUsers() { - String expected = - new JSONObject().put("users", new JSONArray()).toString(); + @DisplayName("user management -> no users") + public void userManagementNoUsers() { + String expected = new JSONObject() + .put("users", new JSONArray()) + .toString(); String url = "/users"; assertThat(new RestApi().get(url)).isEqualTo(expected); @@ -20,279 +21,223 @@ public void noUsers() { @Disabled("Remove to run test") @Test - @DisplayName("add user") - public void addUser() { + @DisplayName("user management -> add user") + public void userManagementAddUser() { String expected = new JSONObject() - .put("name", "Adam") - .put("owes", new JSONObject()) - .put("owedBy", new JSONObject()) - .put("balance", 0.0) - .toString(); + .put("name", "Adam") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject()) + .put("balance", 0.0) + .toString(); String url = "/add"; - JSONObject payload = new JSONObject().put("user", "Adam"); + JSONObject payload = new JSONObject() + .put("user", "Adam"); assertThat(new RestApi().post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("get single user") - public void getSingleUser() { + @DisplayName("user management -> get single user") + public void userManagementGetSingleUser() { String expected = new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Bob") - .put("owes", new JSONObject()) - .put("owedBy", new JSONObject()) - .put("balance", 0.0))) - .toString(); + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject()) + .put("balance", 0.0))) + .toString(); String url = "/users"; - JSONObject payload = - new JSONObject().put("users", new JSONArray().put("Bob")); + JSONObject payload = new JSONObject() + .put("users", new JSONArray() + .put("Bob")); + User adam = User.builder().setName("Adam").build(); + User bob = User.builder().setName("Bob").build(); - assertThat(new RestApi( - User.builder().setName("Adam").build(), - User.builder().setName("Bob").build()) - .get(url, payload)).isEqualTo(expected); + assertThat(new RestApi(adam, bob).get(url, payload)).isEqualTo(expected); } + @Disabled("Remove to run test") @Test - @DisplayName("both users have 0 balance") - public void bothUsersHave0Balance() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put("owes", new JSONObject()) - .put( - "owedBy", - new JSONObject().put("Bob", 3.0)) - .put("balance", 3.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put( - "owes", - new JSONObject().put("Adam", 3.0)) - .put("owedBy", new JSONObject()) - .put("balance", -3.0))) + @DisplayName("iou -> both users have 0 balance") + public void iouBothUsersHave0Balance() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject() + .put("Bob", 3.0)) + .put("balance", 3.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject() + .put("Adam", 3.0)) + .put("owedBy", new JSONObject()) + .put("balance", -3.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Adam") - .put("borrower", "Bob") - .put("amount", 3.0); - - assertThat(new RestApi( - User.builder().setName("Adam").build(), - User.builder().setName("Bob").build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Adam") + .put("borrower", "Bob") + .put("amount", 3.0); + User adam = User.builder().setName("Adam").build(); + User bob = User.builder().setName("Bob").build(); + + assertThat(new RestApi(adam, bob).post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("borrower has negative balance") - public void borrowerHasNegativeBalance() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put("owes", new JSONObject()) - .put( - "owedBy", - new JSONObject().put("Bob", 3.0)) - .put("balance", 3.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put( - "owes", - new JSONObject() - .put("Adam", 3.0) - .put("Chuck", 3.0)) - .put("owedBy", new JSONObject()) - .put("balance", -6.0))) + @DisplayName("iou -> borrower has negative balance") + public void iouBorrowerHasNegativeBalance() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject() + .put("Bob", 3.0)) + .put("balance", 3.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject() + .put("Adam", 3.0) + .put("Chuck", 3.0)) + .put("owedBy", new JSONObject()) + .put("balance", -6.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Adam") - .put("borrower", "Bob") - .put("amount", 3.0); - - assertThat(new RestApi( - User.builder().setName("Adam").build(), - User.builder().setName("Bob").owes("Chuck", 3.0).build(), - User.builder().setName("Chuck").owedBy("Bob", 3.0).build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Adam") + .put("borrower", "Bob") + .put("amount", 3.0); + User adam = User.builder().setName("Adam").build(); + User bob = User.builder().setName("Bob").owes("Chuck", 3.0).build(); + User chuck = User.builder().setName("Chuck").owedBy("Bob", 3.0).build(); + + assertThat(new RestApi(adam, bob, chuck).post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("lender has negative balance") - public void lenderHasNegativeBalance() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put( - "owes", - new JSONObject().put("Bob", 3.0)) - .put( - "owedBy", new JSONObject()) - .put("balance", -3.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put( - "owes", - new JSONObject() - .put("Chuck", 3.0)) - .put( - "owedBy", - new JSONObject().put("Adam", 3.0)) - .put("balance", 0.0))) + @DisplayName("iou -> lender has negative balance") + public void iouLenderHasNegativeBalance() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject() + .put("Bob", 3.0)) + .put("owedBy", new JSONObject()) + .put("balance", -3.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject() + .put("Chuck", 3.0)) + .put("owedBy", new JSONObject() + .put("Adam", 3.0)) + .put("balance", 0.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Bob") - .put("borrower", "Adam") - .put("amount", 3.0); - - assertThat(new RestApi( - User.builder().setName("Adam").build(), - User.builder().setName("Bob").owes("Chuck", 3.0).build(), - User.builder().setName("Chuck").owedBy("Bob", 3.0).build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Bob") + .put("borrower", "Adam") + .put("amount", 3.0); + User adam = User.builder().setName("Adam").build(); + User bob = User.builder().setName("Bob").owes("Chuck", 3.0).build(); + User chuck = User.builder().setName("Chuck").owedBy("Bob", 3.0).build(); + + assertThat(new RestApi(adam, bob, chuck).post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("lender owes borrower") - public void lenderOwesBorrower() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put( - "owes", - new JSONObject().put("Bob", 1.0)) - .put("owedBy", new JSONObject()) - .put("balance", -1.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put("owes", new JSONObject()) - .put( - "owedBy", - new JSONObject().put("Adam", 1.0)) - .put("balance", 1.0))) + @DisplayName("iou -> lender owes borrower") + public void iouLenderOwesBorrower() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject() + .put("Bob", 1.0)) + .put("owedBy", new JSONObject()) + .put("balance", -1.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject() + .put("Adam", 1.0)) + .put("balance", 1.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Adam") - .put("borrower", "Bob") - .put("amount", 2.0); - - assertThat(new RestApi( - User.builder().setName("Adam").owes("Bob", 3.0).build(), - User.builder().setName("Bob").owedBy("Adam", 3.0).build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Adam") + .put("borrower", "Bob") + .put("amount", 2.0); + User adam = User.builder().setName("Adam").owes("Bob", 3.0).build(); + User bob = User.builder().setName("Bob").owedBy("Adam", 3.0).build(); + + assertThat(new RestApi(adam, bob).post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("lender owes borrower less than new loan") - public void lenderOwesBorrowerLessThanNewLoan() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put("owes", new JSONObject()) - .put( - "owedBy", - new JSONObject().put("Bob", 1.0)) - .put("balance", 1.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put( - "owes", - new JSONObject().put("Adam", 1.0)) - .put("owedBy", new JSONObject()) - .put("balance", -1.0))) + @DisplayName("iou -> lender owes borrower less than new loan") + public void iouLenderOwesBorrowerLessThanNewLoan() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject() + .put("Bob", 1.0)) + .put("balance", 1.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject() + .put("Adam", 1.0)) + .put("owedBy", new JSONObject()) + .put("balance", -1.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Adam") - .put("borrower", "Bob") - .put("amount", 4.0); - - assertThat(new RestApi( - User.builder().setName("Adam").owes("Bob", 3.0).build(), - User.builder().setName("Bob").owedBy("Adam", 3.0).build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Adam") + .put("borrower", "Bob") + .put("amount", 4.0); + User adam = User.builder().setName("Adam").owes("Bob", 3.0).build(); + User bob = User.builder().setName("Bob").owedBy("Adam", 3.0).build(); + + assertThat(new RestApi(adam, bob).post(url, payload)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("lender owes borrower same as new loan") - public void lenderOwesBorrowerSameAsNewLoan() { - String expected = - new JSONObject() - .put( - "users", - new JSONArray() - .put( - new JSONObject() - .put("name", "Adam") - .put("owes", new JSONObject()) - .put("owedBy", new JSONObject()) - .put("balance", 0.0)) - .put( - new JSONObject() - .put("name", "Bob") - .put("owes", new JSONObject()) - .put("owedBy", new JSONObject()) - .put("balance", 0.0))) + @DisplayName("iou -> lender owes borrower same as new loan") + public void iouLenderOwesBorrowerSameAsNewLoan() { + String expected = new JSONObject() + .put("users", new JSONArray() + .put(new JSONObject() + .put("name", "Adam") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject()) + .put("balance", 0.0)) + .put(new JSONObject() + .put("name", "Bob") + .put("owes", new JSONObject()) + .put("owedBy", new JSONObject()) + .put("balance", 0.0))) .toString(); String url = "/iou"; - JSONObject payload = - new JSONObject() - .put("lender", "Adam") - .put("borrower", "Bob") - .put("amount", 3.0); - - assertThat(new RestApi( - User.builder().setName("Adam").owes("Bob", 3.0).build(), - User.builder().setName("Bob").owedBy("Adam", 3.0).build()) - .post(url, payload)).isEqualTo(expected); + JSONObject payload = new JSONObject() + .put("lender", "Adam") + .put("borrower", "Bob") + .put("amount", 3.0); + User adam = User.builder().setName("Adam").owes("Bob", 3.0).build(); + User bob = User.builder().setName("Bob").owedBy("Adam", 3.0).build(); + + assertThat(new RestApi(adam, bob).post(url, payload)).isEqualTo(expected); } + } diff --git a/exercises/practice/reverse-string/src/test/java/ReverseStringTest.java b/exercises/practice/reverse-string/src/test/java/ReverseStringTest.java index 64475609c..9ec363898 100644 --- a/exercises/practice/reverse-string/src/test/java/ReverseStringTest.java +++ b/exercises/practice/reverse-string/src/test/java/ReverseStringTest.java @@ -8,42 +8,49 @@ public class ReverseStringTest { @Test @DisplayName("an empty string") - public void testAnEmptyString() { - assertThat(new ReverseString().reverse("")).isEqualTo(""); + public void anEmptyString() { + assertThat(new ReverseString().reverse("")) + .isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("a word") - public void testAWord() { - assertThat(new ReverseString().reverse("robot")).isEqualTo("tobor"); + public void aWord() { + assertThat(new ReverseString().reverse("robot")) + .isEqualTo("tobor"); } @Disabled("Remove to run test") @Test @DisplayName("a capitalized word") - public void testACapitalizedWord() { - assertThat(new ReverseString().reverse("Ramen")).isEqualTo("nemaR"); + public void aCapitalizedWord() { + assertThat(new ReverseString().reverse("Ramen")) + .isEqualTo("nemaR"); } @Disabled("Remove to run test") @Test @DisplayName("a sentence with punctuation") - public void testASentenceWithPunctuation() { - assertThat(new ReverseString().reverse("I'm hungry!")).isEqualTo("!yrgnuh m'I"); + public void aSentenceWithPunctuation() { + assertThat(new ReverseString().reverse("I'm hungry!")) + .isEqualTo("!yrgnuh m'I"); } @Disabled("Remove to run test") @Test @DisplayName("a palindrome") - public void testAPalindrome() { - assertThat(new ReverseString().reverse("racecar")).isEqualTo("racecar"); + public void aPalindrome() { + assertThat(new ReverseString().reverse("racecar")) + .isEqualTo("racecar"); } @Disabled("Remove to run test") @Test @DisplayName("an even-sized word") - public void testAnEvenSizedWord() { - assertThat(new ReverseString().reverse("drawer")).isEqualTo("reward"); + public void anEvenSizedWord() { + assertThat(new ReverseString().reverse("drawer")) + .isEqualTo("reward"); } + } diff --git a/exercises/practice/rna-transcription/src/test/java/RnaTranscriptionTest.java b/exercises/practice/rna-transcription/src/test/java/RnaTranscriptionTest.java index 7b1cc753a..64ce99ae2 100644 --- a/exercises/practice/rna-transcription/src/test/java/RnaTranscriptionTest.java +++ b/exercises/practice/rna-transcription/src/test/java/RnaTranscriptionTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,51 +6,51 @@ public class RnaTranscriptionTest { - private RnaTranscription rnaTranscription; - - @BeforeEach - public void setUp() { - rnaTranscription = new RnaTranscription(); - } - @Test @DisplayName("Empty RNA sequence") - public void testEmptyRnaSequence() { - assertThat(rnaTranscription.transcribe("")).isEmpty(); + public void emptyRnaSequence() { + assertThat(new RnaTranscription().transcribe("")) + .isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("RNA complement of cytosine is guanine") - public void testRnaTranscriptionOfCytosineIsGuanine() { - assertThat(rnaTranscription.transcribe("C")).isEqualTo("G"); + public void rnaComplementOfCytosineIsGuanine() { + assertThat(new RnaTranscription().transcribe("C")) + .isEqualTo("G"); } @Disabled("Remove to run test") @Test @DisplayName("RNA complement of guanine is cytosine") - public void testRnaTranscriptionOfGuanineIsCytosine() { - assertThat(rnaTranscription.transcribe("G")).isEqualTo("C"); + public void rnaComplementOfGuanineIsCytosine() { + assertThat(new RnaTranscription().transcribe("G")) + .isEqualTo("C"); } @Disabled("Remove to run test") @Test @DisplayName("RNA complement of thymine is adenine") - public void testRnaTranscriptionOfThymineIsAdenine() { - assertThat(rnaTranscription.transcribe("T")).isEqualTo("A"); + public void rnaComplementOfThymineIsAdenine() { + assertThat(new RnaTranscription().transcribe("T")) + .isEqualTo("A"); } @Disabled("Remove to run test") @Test @DisplayName("RNA complement of adenine is uracil") - public void testRnaTranscriptionOfAdenineIsUracil() { - assertThat(rnaTranscription.transcribe("A")).isEqualTo("U"); + public void rnaComplementOfAdenineIsUracil() { + assertThat(new RnaTranscription().transcribe("A")) + .isEqualTo("U"); } @Disabled("Remove to run test") @Test @DisplayName("RNA complement") - public void testRnaTranscription() { - assertThat(rnaTranscription.transcribe("ACGTGGTCTTAA")).isEqualTo("UGCACCAGAAUU"); + public void rnaComplement() { + assertThat(new RnaTranscription().transcribe("ACGTGGTCTTAA")) + .isEqualTo("UGCACCAGAAUU"); } + } diff --git a/exercises/practice/robot-simulator/src/test/java/RobotTest.java b/exercises/practice/robot-simulator/src/test/java/RobotTest.java index 5c8edbc0c..08cb2fc18 100644 --- a/exercises/practice/robot-simulator/src/test/java/RobotTest.java +++ b/exercises/practice/robot-simulator/src/test/java/RobotTest.java @@ -6,266 +6,181 @@ public class RobotTest { - /* Create robot */ - @Test - @DisplayName("at origin facing north") - public void atOriginFacingNorth() { - Orientation initialOrientation = Orientation.NORTH; - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, initialOrientation); - - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); + @DisplayName("Create robot -> at origin facing north") + public void createRobotAtOriginFacingNorth() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.NORTH); } @Disabled("Remove to run test") @Test - @DisplayName("at negative position facing south") - public void atNegativePositionFacingSouth() { - GridPosition initialGridPosition = new GridPosition(-1, -1); - Orientation initialOrientation = Orientation.SOUTH; - Robot robot = new Robot(initialGridPosition, initialOrientation); - - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); + @DisplayName("Create robot -> at negative position facing south") + public void createRobotAtNegativePositionFacingSouth() { + Robot robot = new Robot(new GridPosition(-1, -1), Orientation.SOUTH); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(-1, -1)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.SOUTH); } - /* Rotating clockwise */ - @Disabled("Remove to run test") @Test - @DisplayName("changes north to east") - public void changesNorthToEast() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.NORTH); - + @DisplayName("Rotating clockwise -> changes north to east") + public void rotatingClockwiseChangesNorthToEast() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.turnRight(); - - Orientation expectedOrientation = Orientation.EAST; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.EAST); } @Disabled("Remove to run test") @Test - @DisplayName("changes east to south") - public void changesEastToSouth() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.EAST); - + @DisplayName("Rotating clockwise -> changes east to south") + public void rotatingClockwiseChangesEastToSouth() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.turnRight(); - - Orientation expectedOrientation = Orientation.SOUTH; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.SOUTH); } @Disabled("Remove to run test") @Test - @DisplayName("changes south to west") - public void changesSouthToWest() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.SOUTH); - + @DisplayName("Rotating clockwise -> changes south to west") + public void rotatingClockwiseChangesSouthToWest() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.turnRight(); - - Orientation expectedOrientation = Orientation.WEST; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.WEST); } @Disabled("Remove to run test") @Test - @DisplayName("changes west to north") - public void changesWestToNorth() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.WEST); - + @DisplayName("Rotating clockwise -> changes west to north") + public void rotatingClockwiseChangesWestToNorth() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.turnRight(); - - Orientation expectedOrientation = Orientation.NORTH; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.NORTH); } - /* Rotating counter-clockwise */ - @Disabled("Remove to run test") @Test - @DisplayName("changes north to west") - public void changesNorthToWest() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.NORTH); - + @DisplayName("Rotating counter-clockwise -> changes north to west") + public void rotatingCounterClockwiseChangesNorthToWest() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.turnLeft(); - - Orientation expectedOrientation = Orientation.WEST; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.WEST); } @Disabled("Remove to run test") @Test - @DisplayName("changes west to south") - public void changesWestToSouth() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.WEST); - + @DisplayName("Rotating counter-clockwise -> changes west to south") + public void rotatingCounterClockwiseChangesWestToSouth() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.turnLeft(); - - Orientation expectedOrientation = Orientation.SOUTH; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.SOUTH); } @Disabled("Remove to run test") @Test - @DisplayName("changes south to east") - public void changesSouthToEast() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.SOUTH); - + @DisplayName("Rotating counter-clockwise -> changes south to east") + public void rotatingCounterClockwiseChangesSouthToEast() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.turnLeft(); - - Orientation expectedOrientation = Orientation.EAST; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.EAST); } @Disabled("Remove to run test") @Test - @DisplayName("changes east to north") - public void changesEastToNorth() { - GridPosition initialGridPosition = new GridPosition(0, 0); - Robot robot = new Robot(initialGridPosition, Orientation.EAST); - + @DisplayName("Rotating counter-clockwise -> changes east to north") + public void rotatingCounterClockwiseChangesEastToNorth() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.turnLeft(); - - Orientation expectedOrientation = Orientation.NORTH; - assertThat(robot.getGridPosition()).isEqualTo(initialGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.NORTH); } - /* Moving forward one */ - @Disabled("Remove to run test") @Test - @DisplayName("facing north increments Y") - public void facingNorthIncrementsY() { - Orientation initialOrientation = Orientation.NORTH; - Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); - + @DisplayName("Moving forward one -> facing north increments Y") + public void movingForwardOneFacingNorthIncrementsY() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); robot.advance(); - - GridPosition expectedGridPosition = new GridPosition(0, 1); - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, 1)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.NORTH); } @Disabled("Remove to run test") @Test - @DisplayName("facing south decrements Y") - public void facingSouthDecrementsY() { - Orientation initialOrientation = Orientation.SOUTH; - Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); - + @DisplayName("Moving forward one -> facing south decrements Y") + public void movingForwardOneFacingSouthDecrementsY() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.SOUTH); robot.advance(); - - GridPosition expectedGridPosition = new GridPosition(0, -1); - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(0, -1)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.SOUTH); } @Disabled("Remove to run test") @Test - @DisplayName("facing east increments X") - public void facingEastIncrementsX() { - Orientation initialOrientation = Orientation.EAST; - Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); - + @DisplayName("Moving forward one -> facing east increments X") + public void movingForwardOneFacingEastIncrementsX() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.EAST); robot.advance(); - - GridPosition expectedGridPosition = new GridPosition(1, 0); - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(1, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.EAST); } @Disabled("Remove to run test") @Test - @DisplayName("facing west decrements X") - public void facingWestDecrementsX() { - Orientation initialOrientation = Orientation.WEST; - Robot robot = new Robot(new GridPosition(0, 0), initialOrientation); - + @DisplayName("Moving forward one -> facing west decrements X") + public void movingForwardOneFacingWestDecrementsX() { + Robot robot = new Robot(new GridPosition(0, 0), Orientation.WEST); robot.advance(); - - GridPosition expectedGridPosition = new GridPosition(-1, 0); - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(initialOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(-1, 0)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.WEST); } - /* Follow series of instructions */ - @Disabled("Remove to run test") @Test - @DisplayName("moving east and north from README") - public void movingEastAndNorthFromReadme() { + @DisplayName("Follow series of instructions -> moving east and north from README") + public void followSeriesOfInstructionsMovingEastAndNorthFromReadme() { Robot robot = new Robot(new GridPosition(7, 3), Orientation.NORTH); - robot.simulate("RAALAL"); - - GridPosition expectedGridPosition = new GridPosition(9, 4); - Orientation expectedOrientation = Orientation.WEST; - - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(9, 4)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.WEST); } - @Disabled("Remove to run test") @Test - @DisplayName("moving west and north") - public void movingWestAndNorth() { + @DisplayName("Follow series of instructions -> moving west and north") + public void followSeriesOfInstructionsMovingWestAndNorth() { Robot robot = new Robot(new GridPosition(0, 0), Orientation.NORTH); - robot.simulate("LAAARALA"); - - GridPosition expectedGridPosition = new GridPosition(-4, 1); - Orientation expectedOrientation = Orientation.WEST; - - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(-4, 1)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.WEST); } @Disabled("Remove to run test") @Test - @DisplayName("moving west and south") - public void movingWestAndSouth() { + @DisplayName("Follow series of instructions -> moving west and south") + public void followSeriesOfInstructionsMovingWestAndSouth() { Robot robot = new Robot(new GridPosition(2, -7), Orientation.EAST); - robot.simulate("RRAAAAALA"); - - GridPosition expectedGridPosition = new GridPosition(-3, -8); - Orientation expectedOrientation = Orientation.SOUTH; - - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(-3, -8)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.SOUTH); } @Disabled("Remove to run test") @Test - @DisplayName("moving east and north") - public void movingEastAndNorth() { + @DisplayName("Follow series of instructions -> moving east and north") + public void followSeriesOfInstructionsMovingEastAndNorth() { Robot robot = new Robot(new GridPosition(8, 4), Orientation.SOUTH); - robot.simulate("LAAARRRALLLL"); - - GridPosition expectedGridPosition = new GridPosition(11, 5); - Orientation expectedOrientation = Orientation.NORTH; - - assertThat(robot.getGridPosition()).isEqualTo(expectedGridPosition); - assertThat(robot.getOrientation()).isEqualTo(expectedOrientation); + assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(11, 5)); + assertThat(robot.getOrientation()).isEqualTo(Orientation.NORTH); } } diff --git a/exercises/practice/roman-numerals/src/test/java/RomanNumeralsTest.java b/exercises/practice/roman-numerals/src/test/java/RomanNumeralsTest.java index 8b7c21da8..8a4b8ab0e 100644 --- a/exercises/practice/roman-numerals/src/test/java/RomanNumeralsTest.java +++ b/exercises/practice/roman-numerals/src/test/java/RomanNumeralsTest.java @@ -6,220 +6,219 @@ public class RomanNumeralsTest { - private RomanNumerals romanNumerals; - @Test @DisplayName("1 is I") - public void test1ToRomanNumberI() { - romanNumerals = new RomanNumerals(1); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("I"); + public void test1IsI() { + assertThat(new RomanNumerals(1).getRomanNumeral()) + .isEqualTo("I"); } @Disabled("Remove to run test") @Test @DisplayName("2 is II") - public void test2ToRomanNumberII() { - romanNumerals = new RomanNumerals(2); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("II"); + public void test2IsIi() { + assertThat(new RomanNumerals(2).getRomanNumeral()) + .isEqualTo("II"); } @Disabled("Remove to run test") @Test @DisplayName("3 is III") - public void test3ToRomanNumberIII() { - romanNumerals = new RomanNumerals(3); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("III"); + public void test3IsIii() { + assertThat(new RomanNumerals(3).getRomanNumeral()) + .isEqualTo("III"); } @Disabled("Remove to run test") @Test @DisplayName("4 is IV") - public void test4ToRomanNumberIV() { - romanNumerals = new RomanNumerals(4); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("IV"); + public void test4IsIv() { + assertThat(new RomanNumerals(4).getRomanNumeral()) + .isEqualTo("IV"); } @Disabled("Remove to run test") @Test @DisplayName("5 is V") - public void test5ToRomanNumberV() { - romanNumerals = new RomanNumerals(5); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("V"); + public void test5IsV() { + assertThat(new RomanNumerals(5).getRomanNumeral()) + .isEqualTo("V"); } @Disabled("Remove to run test") @Test @DisplayName("6 is VI") - public void test6ToRomanNumberVI() { - romanNumerals = new RomanNumerals(6); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("VI"); + public void test6IsVi() { + assertThat(new RomanNumerals(6).getRomanNumeral()) + .isEqualTo("VI"); } @Disabled("Remove to run test") @Test @DisplayName("9 is IX") - public void test9ToRomanNumberIX() { - romanNumerals = new RomanNumerals(9); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("IX"); + public void test9IsIx() { + assertThat(new RomanNumerals(9).getRomanNumeral()) + .isEqualTo("IX"); } @Disabled("Remove to run test") @Test @DisplayName("16 is XVI") - public void test16ToRomanNumberXVI() { - romanNumerals = new RomanNumerals(16); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("XVI"); + public void test16IsXvi() { + assertThat(new RomanNumerals(16).getRomanNumeral()) + .isEqualTo("XVI"); } @Disabled("Remove to run test") @Test @DisplayName("27 is XXVII") - public void test27ToRomanNumberXXVII() { - romanNumerals = new RomanNumerals(27); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("XXVII"); + public void test27IsXxvii() { + assertThat(new RomanNumerals(27).getRomanNumeral()) + .isEqualTo("XXVII"); } @Disabled("Remove to run test") @Test @DisplayName("48 is XLVIII") - public void test48ToRomanNumberXLVIII() { - romanNumerals = new RomanNumerals(48); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("XLVIII"); + public void test48IsXlviii() { + assertThat(new RomanNumerals(48).getRomanNumeral()) + .isEqualTo("XLVIII"); } @Disabled("Remove to run test") @Test @DisplayName("49 is XLIX") - public void test49ToRomanNumberXLIX() { - romanNumerals = new RomanNumerals(49); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("XLIX"); + public void test49IsXlix() { + assertThat(new RomanNumerals(49).getRomanNumeral()) + .isEqualTo("XLIX"); } @Disabled("Remove to run test") @Test @DisplayName("59 is LIX") - public void test59ToRomanNumberLIX() { - romanNumerals = new RomanNumerals(59); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("LIX"); + public void test59IsLix() { + assertThat(new RomanNumerals(59).getRomanNumeral()) + .isEqualTo("LIX"); } @Disabled("Remove to run test") @Test @DisplayName("66 is LXVI") - public void test66ToRomanNumberLXVI() { - romanNumerals = new RomanNumerals(66); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("LXVI"); + public void test66IsLxvi() { + assertThat(new RomanNumerals(66).getRomanNumeral()) + .isEqualTo("LXVI"); } @Disabled("Remove to run test") @Test @DisplayName("93 is XCIII") - public void test93ToRomanNumberXCIII() { - romanNumerals = new RomanNumerals(93); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("XCIII"); + public void test93IsXciii() { + assertThat(new RomanNumerals(93).getRomanNumeral()) + .isEqualTo("XCIII"); } @Disabled("Remove to run test") @Test @DisplayName("141 is CXLI") - public void test141ToRomanNumberCXLI() { - romanNumerals = new RomanNumerals(141); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("CXLI"); + public void test141IsCxli() { + assertThat(new RomanNumerals(141).getRomanNumeral()) + .isEqualTo("CXLI"); } @Disabled("Remove to run test") @Test @DisplayName("163 is CLXIII") - public void test163ToRomanNumberCLXIII() { - romanNumerals = new RomanNumerals(163); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("CLXIII"); + public void test163IsClxiii() { + assertThat(new RomanNumerals(163).getRomanNumeral()) + .isEqualTo("CLXIII"); } @Disabled("Remove to run test") @Test @DisplayName("166 is CLXVI") - public void test166ToRomanNumberCLXVI() { - romanNumerals = new RomanNumerals(166); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("CLXVI"); + public void test166IsClxvi() { + assertThat(new RomanNumerals(166).getRomanNumeral()) + .isEqualTo("CLXVI"); } @Disabled("Remove to run test") @Test @DisplayName("402 is CDII") - public void test402ToRomanNumberCDII() { - romanNumerals = new RomanNumerals(402); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("CDII"); + public void test402IsCdii() { + assertThat(new RomanNumerals(402).getRomanNumeral()) + .isEqualTo("CDII"); } @Disabled("Remove to run test") @Test @DisplayName("575 is DLXXV") - public void test575ToRomanNumberDLXXV() { - romanNumerals = new RomanNumerals(575); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("DLXXV"); + public void test575IsDlxxv() { + assertThat(new RomanNumerals(575).getRomanNumeral()) + .isEqualTo("DLXXV"); } @Disabled("Remove to run test") @Test @DisplayName("666 is DCLXVI") - public void test666ToRomanNumberDCLXVI() { - romanNumerals = new RomanNumerals(666); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("DCLXVI"); + public void test666IsDclxvi() { + assertThat(new RomanNumerals(666).getRomanNumeral()) + .isEqualTo("DCLXVI"); } @Disabled("Remove to run test") @Test @DisplayName("911 is CMXI") - public void test911ToRomanNumberCMXI() { - romanNumerals = new RomanNumerals(911); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("CMXI"); + public void test911IsCmxi() { + assertThat(new RomanNumerals(911).getRomanNumeral()) + .isEqualTo("CMXI"); } @Disabled("Remove to run test") @Test @DisplayName("1024 is MXXIV") - public void test1024ToRomanNumberMXXIV() { - romanNumerals = new RomanNumerals(1024); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MXXIV"); + public void test1024IsMxxiv() { + assertThat(new RomanNumerals(1024).getRomanNumeral()) + .isEqualTo("MXXIV"); } @Disabled("Remove to run test") @Test @DisplayName("1666 is MDCLXVI") - public void test1666ToRomanNumberMDCLXVI() { - romanNumerals = new RomanNumerals(1666); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MDCLXVI"); + public void test1666IsMdclxvi() { + assertThat(new RomanNumerals(1666).getRomanNumeral()) + .isEqualTo("MDCLXVI"); } @Disabled("Remove to run test") @Test @DisplayName("3000 is MMM") - public void test3000ToRomanNumberMMM() { - romanNumerals = new RomanNumerals(3000); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MMM"); + public void test3000IsMmm() { + assertThat(new RomanNumerals(3000).getRomanNumeral()) + .isEqualTo("MMM"); } @Disabled("Remove to run test") @Test @DisplayName("3001 is MMMI") - public void test3001ToRomanNumberMMMI() { - romanNumerals = new RomanNumerals(3001); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MMMI"); + public void test3001IsMmmi() { + assertThat(new RomanNumerals(3001).getRomanNumeral()) + .isEqualTo("MMMI"); } @Disabled("Remove to run test") @Test @DisplayName("3888 is MMMDCCCLXXXVIII") - public void test3888ToRomanNumberMMMDCCCLXXXVIII() { - romanNumerals = new RomanNumerals(3888); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MMMDCCCLXXXVIII"); + public void test3888IsMmmdccclxxxviii() { + assertThat(new RomanNumerals(3888).getRomanNumeral()) + .isEqualTo("MMMDCCCLXXXVIII"); } @Disabled("Remove to run test") @Test @DisplayName("3999 is MMMCMXCIX") - public void test3999ToRomanNumberMMMCMXCIX() { - romanNumerals = new RomanNumerals(3999); - assertThat(romanNumerals.getRomanNumeral()).isEqualTo("MMMCMXCIX"); + public void test3999IsMmmcmxcix() { + assertThat(new RomanNumerals(3999).getRomanNumeral()) + .isEqualTo("MMMCMXCIX"); } + } diff --git a/exercises/practice/rotational-cipher/src/test/java/RotationalCipherTest.java b/exercises/practice/rotational-cipher/src/test/java/RotationalCipherTest.java index be75833ab..a73378421 100644 --- a/exercises/practice/rotational-cipher/src/test/java/RotationalCipherTest.java +++ b/exercises/practice/rotational-cipher/src/test/java/RotationalCipherTest.java @@ -6,85 +6,83 @@ public class RotationalCipherTest { - private RotationalCipher rotationalCipher; - @Test @DisplayName("rotate a by 0, same output as input") - public void rotateSingleCharacterBy0() { - rotationalCipher = new RotationalCipher(0); - assertThat(rotationalCipher.rotate("a")).isEqualTo("a"); + public void rotateABy0SameOutputAsInput() { + assertThat(new RotationalCipher(0).rotate("a")) + .isEqualTo("a"); } @Disabled("Remove to run test") @Test @DisplayName("rotate a by 1") - public void rotateSingleCharacterBy1() { - rotationalCipher = new RotationalCipher(1); - assertThat(rotationalCipher.rotate("a")).isEqualTo("b"); + public void rotateABy1() { + assertThat(new RotationalCipher(1).rotate("a")) + .isEqualTo("b"); } @Disabled("Remove to run test") @Test @DisplayName("rotate a by 26, same output as input") - public void rotateSingleCharacterBy26() { - rotationalCipher = new RotationalCipher(26); - assertThat(rotationalCipher.rotate("a")).isEqualTo("a"); + public void rotateABy26SameOutputAsInput() { + assertThat(new RotationalCipher(26).rotate("a")) + .isEqualTo("a"); } @Disabled("Remove to run test") @Test @DisplayName("rotate m by 13") - public void rotateSingleCharacterBy13() { - rotationalCipher = new RotationalCipher(13); - assertThat(rotationalCipher.rotate("m")).isEqualTo("z"); + public void rotateMBy13() { + assertThat(new RotationalCipher(13).rotate("m")) + .isEqualTo("z"); } @Disabled("Remove to run test") @Test @DisplayName("rotate n by 13 with wrap around alphabet") - public void rotateSingleCharacterWithWrapAround() { - rotationalCipher = new RotationalCipher(13); - assertThat(rotationalCipher.rotate("n")).isEqualTo("a"); + public void rotateNBy13WithWrapAroundAlphabet() { + assertThat(new RotationalCipher(13).rotate("n")) + .isEqualTo("a"); } @Disabled("Remove to run test") @Test @DisplayName("rotate capital letters") public void rotateCapitalLetters() { - rotationalCipher = new RotationalCipher(5); - assertThat(rotationalCipher.rotate("OMG")).isEqualTo("TRL"); + assertThat(new RotationalCipher(5).rotate("OMG")) + .isEqualTo("TRL"); } @Disabled("Remove to run test") @Test @DisplayName("rotate spaces") public void rotateSpaces() { - rotationalCipher = new RotationalCipher(5); - assertThat(rotationalCipher.rotate("O M G")).isEqualTo("T R L"); + assertThat(new RotationalCipher(5).rotate("O M G")) + .isEqualTo("T R L"); } @Disabled("Remove to run test") @Test @DisplayName("rotate numbers") public void rotateNumbers() { - rotationalCipher = new RotationalCipher(4); - assertThat(rotationalCipher.rotate("Testing 1 2 3 testing")).isEqualTo("Xiwxmrk 1 2 3 xiwxmrk"); + assertThat(new RotationalCipher(4).rotate("Testing 1 2 3 testing")) + .isEqualTo("Xiwxmrk 1 2 3 xiwxmrk"); } @Disabled("Remove to run test") @Test @DisplayName("rotate punctuation") public void rotatePunctuation() { - rotationalCipher = new RotationalCipher(21); - assertThat(rotationalCipher.rotate("Let's eat, Grandma!")).isEqualTo("Gzo'n zvo, Bmviyhv!"); + assertThat(new RotationalCipher(21).rotate("Let's eat, Grandma!")) + .isEqualTo("Gzo'n zvo, Bmviyhv!"); } @Disabled("Remove to run test") @Test @DisplayName("rotate all letters") public void rotateAllLetters() { - rotationalCipher = new RotationalCipher(13); - assertThat(rotationalCipher.rotate("Gur dhvpx oebja sbk whzcf bire gur ynml qbt.")) - .isEqualTo("The quick brown fox jumps over the lazy dog."); + assertThat(new RotationalCipher(13).rotate("The quick brown fox jumps over the lazy dog.")) + .isEqualTo("Gur dhvpx oebja sbk whzcf bire gur ynml qbt."); } + } diff --git a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java index 47373f2e2..23dff968e 100644 --- a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java +++ b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,106 +5,136 @@ import static org.assertj.core.api.Assertions.assertThat; public class RunLengthEncodingTest { - private RunLengthEncoding runLengthEncoding; - @BeforeEach - public void setUp() { - runLengthEncoding = new RunLengthEncoding(); - } + private RunLengthEncoding runLengthEncoding = new RunLengthEncoding(); @Test - @DisplayName("empty string") - public void encodeEmpty() { - assertThat(runLengthEncoding.encode("")).isEmpty(); + @DisplayName("run-length encode a string -> empty string") + public void runLengthEncodeAStringEmptyString() { + + assertThat(runLengthEncoding.encode("")) + .isEqualTo(""); + } @Disabled("Remove to run test") @Test - @DisplayName("single characters only are encoded without count") - public void encodeWithOnlySingleValues() { - assertThat(runLengthEncoding.encode("XYZ")).isEqualTo("XYZ"); + @DisplayName("run-length encode a string -> single characters only are encoded without count") + public void runLengthEncodeAStringSingleCharactersOnlyAreEncodedWithoutCount() { + + assertThat(runLengthEncoding.encode("XYZ")) + .isEqualTo("XYZ"); + } @Disabled("Remove to run test") @Test - @DisplayName("string with no single characters") - public void encodeWithNoSingleValues() { - assertThat(runLengthEncoding.encode("AABBBCCCC")).isEqualTo("2A3B4C"); + @DisplayName("run-length encode a string -> string with no single characters") + public void runLengthEncodeAStringStringWithNoSingleCharacters() { + + assertThat(runLengthEncoding.encode("AABBBCCCC")) + .isEqualTo("2A3B4C"); + } @Disabled("Remove to run test") @Test - @DisplayName("single characters mixed with repeated characters") - public void encodeWithMixedValues() { - assertThat(runLengthEncoding.encode( - "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")) - .isEqualTo("12WB12W3B24WB"); + @DisplayName("run-length encode a string -> single characters mixed with repeated characters") + public void runLengthEncodeAStringSingleCharactersMixedWithRepeatedCharacters() { + + assertThat(runLengthEncoding.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")) + .isEqualTo("12WB12W3B24WB"); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple whitespace mixed in string") - public void encodeWithWhitespaceValues() { + @DisplayName("run-length encode a string -> multiple whitespace mixed in string") + public void runLengthEncodeAStringMultipleWhitespaceMixedInString() { + assertThat(runLengthEncoding.encode(" hsqq qww ")) - .isEqualTo("2 hs2q q2w2 "); + .isEqualTo("2 hs2q q2w2 "); + } @Disabled("Remove to run test") @Test - @DisplayName("lowercase characters") - public void encodeWithLowercaseValues() { - assertThat(runLengthEncoding.encode("aabbbcccc")).isEqualTo("2a3b4c"); + @DisplayName("run-length encode a string -> lowercase characters") + public void runLengthEncodeAStringLowercaseCharacters() { + + assertThat(runLengthEncoding.encode("aabbbcccc")) + .isEqualTo("2a3b4c"); + } @Disabled("Remove to run test") @Test - @DisplayName("empty string") - public void decodeEmpty() { - assertThat(runLengthEncoding.decode("")).isEmpty(); + @DisplayName("run-length decode a string -> empty string") + public void runLengthDecodeAStringEmptyString() { + + assertThat(runLengthEncoding.decode("")) + .isEqualTo(""); + } @Disabled("Remove to run test") @Test - @DisplayName("single characters only") - public void decodeWithOnlySingleValues() { - assertThat(runLengthEncoding.decode("XYZ")).isEqualTo("XYZ"); + @DisplayName("run-length decode a string -> single characters only") + public void runLengthDecodeAStringSingleCharactersOnly() { + + assertThat(runLengthEncoding.decode("XYZ")) + .isEqualTo("XYZ"); + } @Disabled("Remove to run test") @Test - @DisplayName("string with no single characters") - public void decodeWithNoSingleValues() { - assertThat(runLengthEncoding.decode("2A3B4C")).isEqualTo("AABBBCCCC"); + @DisplayName("run-length decode a string -> string with no single characters") + public void runLengthDecodeAStringStringWithNoSingleCharacters() { + + assertThat(runLengthEncoding.decode("2A3B4C")) + .isEqualTo("AABBBCCCC"); + } @Disabled("Remove to run test") @Test - @DisplayName("single characters with repeated characters") - public void decodeWithMixedValues() { + @DisplayName("run-length decode a string -> single characters with repeated characters") + public void runLengthDecodeAStringSingleCharactersWithRepeatedCharacters() { + assertThat(runLengthEncoding.decode("12WB12W3B24WB")) - .isEqualTo("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); + .isEqualTo("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple whitespace mixed in string") - public void decodeWithWhitespaceValues() { - assertThat(runLengthEncoding.decode("2 hs2q q2w2 ")).isEqualTo(" hsqq qww "); + @DisplayName("run-length decode a string -> multiple whitespace mixed in string") + public void runLengthDecodeAStringMultipleWhitespaceMixedInString() { + + assertThat(runLengthEncoding.decode("2 hs2q q2w2 ")) + .isEqualTo(" hsqq qww "); + } @Disabled("Remove to run test") @Test - @DisplayName("lowercase string") - public void decodeWithLowercaseValues() { - assertThat(runLengthEncoding.decode("2a3b4c")).isEqualTo("aabbbcccc"); + @DisplayName("run-length decode a string -> lowercase string") + public void runLengthDecodeAStringLowercaseString() { + + assertThat(runLengthEncoding.decode("2a3b4c")) + .isEqualTo("aabbbcccc"); + } @Disabled("Remove to run test") @Test - @DisplayName("encode followed by decode gives original string") - public void encodeThenDecode() { - String inOut = "zzz ZZ zZ"; - String encoded = runLengthEncoding.encode(inOut); - assertThat(runLengthEncoding.decode(encoded)).isEqualTo(inOut); + @DisplayName("encode and then decode -> encode followed by decode gives original string") + public void encodeAndThenDecodeEncodeFollowedByDecodeGivesOriginalString() { + + assertThat(runLengthEncoding.decode(runLengthEncoding.encode("zzz ZZ zZ"))) + .isEqualTo("zzz ZZ zZ"); + } + } diff --git a/exercises/practice/saddle-points/src/test/java/MatrixTest.java b/exercises/practice/saddle-points/src/test/java/MatrixTest.java index 56b5087fc..d948953e8 100644 --- a/exercises/practice/saddle-points/src/test/java/MatrixTest.java +++ b/exercises/practice/saddle-points/src/test/java/MatrixTest.java @@ -2,10 +2,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; +import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -14,147 +11,118 @@ public class MatrixTest { @Test @DisplayName("Can identify single saddle point") - public void testCanIdentifySingleSaddlePoint() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(9, 8, 7), - Arrays.asList(5, 3, 2), - Arrays.asList(6, 6, 7) + public void canIdentifySingleSaddlePoint() { + Matrix matrix = new Matrix(List.of( + List.of(9, 8, 7), + List.of(5, 3, 2), + List.of(6, 6, 7) )); - Set expectedSaddlePoints = Collections.singleton(new MatrixCoordinate(2, 1)); - - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(2, 1))); } @Disabled("Remove to run test") @Test @DisplayName("Can identify that empty matrix has no saddle points") - public void testCanIdentifyThatEmptyMatrixHasNoSaddlePoints() { - Matrix matrix = new Matrix(new ArrayList<>()); - - Set expectedSaddlePoints = Collections.emptySet(); + public void canIdentifyThatEmptyMatrixHasNoSaddlePoints() { + Matrix matrix = new Matrix(List.of(List.of())); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of()); } @Disabled("Remove to run test") @Test @DisplayName("Can identify lack of saddle points when there are none") - public void testCanIdentifyLackOfSaddlePointsWhenThereAreNone() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(1, 2, 3), - Arrays.asList(3, 1, 2), - Arrays.asList(2, 3, 1) + public void canIdentifyLackOfSaddlePointsWhenThereAreNone() { + Matrix matrix = new Matrix(List.of( + List.of(1, 2, 3), + List.of(3, 1, 2), + List.of(2, 3, 1) )); - Set expectedSaddlePoints = Collections.emptySet(); - - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of()); } @Disabled("Remove to run test") @Test @DisplayName("Can identify multiple saddle points in a column") - public void testCanIdentifyMultipleSaddlePointsInAColumn() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(4, 5, 4), - Arrays.asList(3, 5, 5), - Arrays.asList(1, 5, 4) - )); - - Set expectedSaddlePoints = new HashSet<>(Arrays.asList( - new MatrixCoordinate(1, 2), - new MatrixCoordinate(2, 2), - new MatrixCoordinate(3, 2) + public void canIdentifyMultipleSaddlePointsInAColumn() { + Matrix matrix = new Matrix(List.of( + List.of(4, 5, 4), + List.of(3, 5, 5), + List.of(1, 5, 4) )); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(1, 2), new MatrixCoordinate(2, 2), new MatrixCoordinate(3, 2))); } @Disabled("Remove to run test") @Test - @DisplayName("Can identify multiple saddle points in a Row") - public void testCanIdentifyMultipleSaddlePointsInARow() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(6, 7, 8), - Arrays.asList(5, 5, 5), - Arrays.asList(7, 5, 6) - )); - - Set expectedSaddlePoints = new HashSet<>(Arrays.asList( - new MatrixCoordinate(2, 1), - new MatrixCoordinate(2, 2), - new MatrixCoordinate(2, 3) + @DisplayName("Can identify multiple saddle points in a row") + public void canIdentifyMultipleSaddlePointsInARow() { + Matrix matrix = new Matrix(List.of( + List.of(6, 7, 8), + List.of(5, 5, 5), + List.of(7, 5, 6) )); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(2, 1), new MatrixCoordinate(2, 2), new MatrixCoordinate(2, 3))); } @Disabled("Remove to run test") @Test @DisplayName("Can identify saddle point in bottom right corner") - public void testCanIdentifySaddlePointInBottomRightCorner() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(8, 7, 9), - Arrays.asList(6, 7, 6), - Arrays.asList(3, 2, 5) + public void canIdentifySaddlePointInBottomRightCorner() { + Matrix matrix = new Matrix(List.of( + List.of(8, 7, 9), + List.of(6, 7, 6), + List.of(3, 2, 5) )); - Set expectedSaddlePoints = Collections.singleton(new MatrixCoordinate(3, 3)); - - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(3, 3))); } @Disabled("Remove to run test") @Test @DisplayName("Can identify saddle points in a non square matrix") - public void testCanIdentifySaddlePointsInANonSquareMatrix() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(3, 1, 3), - Arrays.asList(3, 2, 4) - )); - - Set expectedSaddlePoints = new HashSet<>(Arrays.asList( - new MatrixCoordinate(1, 3), - new MatrixCoordinate(1, 1) - )); + public void canIdentifySaddlePointsInANonSquareMatrix() { + Matrix matrix = new Matrix(List.of(List.of(3, 1, 3), List.of(3, 2, 4))); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(1, 3), new MatrixCoordinate(1, 1))); } @Disabled("Remove to run test") @Test - @DisplayName("Can identify that saddle points in a single column matrix are those with the minimum value") - public void testCanIdentifyThatSaddlePointsInASingleColumnMatrixAreThoseWithMinimumValue() { - Matrix matrix = new Matrix(Arrays.asList( - Collections.singletonList(2), - Collections.singletonList(1), - Collections.singletonList(4), - Collections.singletonList(1) - )); - - Set expectedSaddlePoints = new HashSet<>(Arrays.asList( - new MatrixCoordinate(2, 1), - new MatrixCoordinate(4, 1) + @DisplayName("Can identify that saddle points in a single column matrix are those " + + "with the minimum value") + public void canIdentifyThatSaddlePointsInASingleColumnMatrixAreThoseWithTheMi() { + Matrix matrix = new Matrix(List.of( + List.of(2), + List.of(1), + List.of(4), + List.of(1) )); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(2, 1), new MatrixCoordinate(4, 1))); } @Disabled("Remove to run test") @Test - @DisplayName("Can identify that saddle points in a single row matrix are those with the maximum value") - public void testCanIdentifyThatSaddlePointsInASingleRowMatrixAreThoseWithMaximumValue() { - Matrix matrix = new Matrix(Arrays.asList( - Arrays.asList(2, 5, 3, 5) - )); - - Set expectedSaddlePoints = new HashSet<>(Arrays.asList( - new MatrixCoordinate(1, 2), - new MatrixCoordinate(1, 4) - )); + @DisplayName("Can identify that saddle points in a single row matrix are those with " + + "the maximum value") + public void canIdentifyThatSaddlePointsInASingleRowMatrixAreThoseWithTheMaxim() { + Matrix matrix = new Matrix(List.of(List.of(2, 5, 3, 5))); - assertThat(matrix.getSaddlePoints()).isEqualTo(expectedSaddlePoints); + assertThat(matrix.getSaddlePoints()) + .isEqualTo(Set.of(new MatrixCoordinate(1, 2), new MatrixCoordinate(1, 4))); } } diff --git a/exercises/practice/satellite/src/test/java/SatelliteTest.java b/exercises/practice/satellite/src/test/java/SatelliteTest.java index a97672643..2341a15cd 100644 --- a/exercises/practice/satellite/src/test/java/SatelliteTest.java +++ b/exercises/practice/satellite/src/test/java/SatelliteTest.java @@ -1,14 +1,15 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import java.util.List; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class SatelliteTest { - Satellite satellite = new Satellite(); + + private Satellite satellite = new Satellite(); @Test @DisplayName("Empty tree") @@ -54,14 +55,13 @@ public void treeWithManyItems() { @Disabled("Remove to run test") @Test @DisplayName("Reject traversals of different length") - public void rejectTraversalsOfDifferentLengths() { + public void rejectTraversalsOfDifferentLength() { List preorder = List.of('a', 'b'); List inorder = List.of('b', 'a', 'r'); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> satellite.treeFromTraversals(preorder, inorder)) .withMessage("traversals must have the same length"); - } @Disabled("Remove to run test") @@ -88,45 +88,4 @@ public void rejectTraversalsWithRepeatedItems() { .withMessage("traversals must contain unique items"); } - @Disabled("Remove to run test") - @Test - @DisplayName("A degenerate binary tree") - public void degenerateBinaryTree() { - List preorder = List.of('a', 'b', 'c', 'd'); - List inorder = List.of('d', 'c', 'b', 'a'); - - Tree tree = satellite.treeFromTraversals(preorder, inorder); - - assertThat(tree.preorder()).containsExactlyElementsOf(preorder); - assertThat(tree.inorder()).containsExactlyElementsOf(inorder); - assertThat(tree.postorder()).containsExactly('d', 'c', 'b', 'a'); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("Another degenerate binary tree") - public void anotherDegenerateBinaryTree() { - List preorder = List.of('a', 'b', 'c', 'd'); - List inorder = List.of('a', 'b', 'c', 'd'); - - Tree tree = satellite.treeFromTraversals(preorder, inorder); - - assertThat(tree.preorder()).containsExactlyElementsOf(preorder); - assertThat(tree.inorder()).containsExactlyElementsOf(inorder); - assertThat(tree.postorder()).containsExactly('d', 'c', 'b', 'a'); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("Tree with many more items") - public void treeWithManyMoreItems() { - List preorder = List.of('a', 'b', 'd', 'g', 'h', 'c', 'e', 'f', 'i'); - List inorder = List.of('g', 'd', 'h', 'b', 'a', 'e', 'c', 'i', 'f'); - - Tree tree = satellite.treeFromTraversals(preorder, inorder); - - assertThat(tree.preorder()).containsExactlyElementsOf(preorder); - assertThat(tree.inorder()).containsExactlyElementsOf(inorder); - assertThat(tree.postorder()).containsExactly('g', 'h', 'd', 'b', 'e', 'i', 'f', 'c', 'a'); - } } diff --git a/exercises/practice/say/src/test/java/SayTest.java b/exercises/practice/say/src/test/java/SayTest.java index 2a999c517..67ee85851 100644 --- a/exercises/practice/say/src/test/java/SayTest.java +++ b/exercises/practice/say/src/test/java/SayTest.java @@ -2,145 +2,164 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; -public class SayTest { +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - private Say say = new Say(); +public class SayTest { @Test @DisplayName("zero") public void zero() { - assertThat(say.say(0)).isEqualTo("zero"); + assertThat(new Say().say(0)) + .isEqualTo("zero"); } @Disabled("Remove to run test") @Test @DisplayName("one") public void one() { - assertThat(say.say(1)).isEqualTo("one"); + assertThat(new Say().say(1)) + .isEqualTo("one"); } @Disabled("Remove to run test") @Test @DisplayName("fourteen") public void fourteen() { - assertThat(say.say(14)).isEqualTo("fourteen"); + assertThat(new Say().say(14)) + .isEqualTo("fourteen"); } @Disabled("Remove to run test") @Test @DisplayName("twenty") public void twenty() { - assertThat(say.say(20)).isEqualTo("twenty"); + assertThat(new Say().say(20)) + .isEqualTo("twenty"); } @Disabled("Remove to run test") @Test @DisplayName("twenty-two") public void twentyTwo() { - assertThat(say.say(22)).isEqualTo("twenty-two"); + assertThat(new Say().say(22)) + .isEqualTo("twenty-two"); } @Disabled("Remove to run test") @Test @DisplayName("thirty") public void thirty() { - assertThat(say.say(30)).isEqualTo("thirty"); + assertThat(new Say().say(30)) + .isEqualTo("thirty"); } @Disabled("Remove to run test") @Test @DisplayName("ninety-nine") public void ninetyNine() { - assertThat(say.say(99)).isEqualTo("ninety-nine"); + assertThat(new Say().say(99)) + .isEqualTo("ninety-nine"); } @Disabled("Remove to run test") @Test @DisplayName("one hundred") public void oneHundred() { - assertThat(say.say(100)).isEqualTo("one hundred"); + assertThat(new Say().say(100)) + .isEqualTo("one hundred"); } @Disabled("Remove to run test") @Test @DisplayName("one hundred twenty-three") public void oneHundredTwentyThree() { - assertThat(say.say(123)).isEqualTo("one hundred twenty-three"); + assertThat(new Say().say(123)) + .isEqualTo("one hundred twenty-three"); } @Disabled("Remove to run test") @Test @DisplayName("two hundred") public void twoHundred() { - assertThat(say.say(200)).isEqualTo("two hundred"); + assertThat(new Say().say(200)) + .isEqualTo("two hundred"); } @Disabled("Remove to run test") @Test @DisplayName("nine hundred ninety-nine") public void nineHundredNinetyNine() { - assertThat(say.say(999)).isEqualTo("nine hundred ninety-nine"); + assertThat(new Say().say(999)) + .isEqualTo("nine hundred ninety-nine"); } @Disabled("Remove to run test") @Test @DisplayName("one thousand") public void oneThousand() { - assertThat(say.say(1_000)).isEqualTo("one thousand"); + assertThat(new Say().say(1000)) + .isEqualTo("one thousand"); } @Disabled("Remove to run test") @Test @DisplayName("one thousand two hundred thirty-four") public void oneThousandTwoHundredThirtyFour() { - assertThat(say.say(1_234)).isEqualTo("one thousand two hundred thirty-four"); + assertThat(new Say().say(1234)) + .isEqualTo("one thousand two hundred thirty-four"); } @Disabled("Remove to run test") @Test @DisplayName("one million") public void oneMillion() { - assertThat(say.say(1_000_000)).isEqualTo("one million"); + assertThat(new Say().say(1000000)) + .isEqualTo("one million"); } @Disabled("Remove to run test") @Test @DisplayName("one million two thousand three hundred forty-five") public void oneMillionTwoThousandThreeHundredFortyFive() { - assertThat(say.say(1_002_345)).isEqualTo("one million two thousand three hundred forty-five"); + assertThat(new Say().say(1002345)) + .isEqualTo("one million two thousand three hundred forty-five"); } @Disabled("Remove to run test") @Test @DisplayName("one billion") public void oneBillion() { - assertThat(say.say(1_000_000_000)).isEqualTo("one billion"); + assertThat(new Say().say(1000000000)) + .isEqualTo("one billion"); } @Disabled("Remove to run test") @Test @DisplayName("a big number") - public void nineHundredEightySevenBillionSixHundredFiftyFourThreeHundredTwentyOneThousandOneHundredTwentyThree() { - assertThat(say.say(987_654_321_123L)) - .isEqualTo("nine hundred eighty-seven billion six hundred fifty-four million" + - " three hundred twenty-one thousand one hundred twenty-three"); + public void aBigNumber() { + assertThat(new Say().say(987654321123L)) + .isEqualTo("nine hundred eighty-seven billion six hundred fifty-four million " + + "three hundred twenty-one thousand one hundred twenty-three"); } @Disabled("Remove to run test") @Test @DisplayName("numbers below zero are out of range") - public void illegalNegativeNumber() { + public void numbersBelowZeroAreOutOfRange() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> say.say(-1)); + .isThrownBy(() -> new Say().say(-1)) + .withMessage("input out of range"); } @Disabled("Remove to run test") @Test @DisplayName("numbers above 999,999,999,999 are out of range") - public void illegalTooBigNumber() { + public void numbersAbove999999999999AreOutOfRange() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> say.say(1_000_000_000_000L)); + .isThrownBy(() -> new Say().say(1000000000000L)) + .withMessage("input out of range"); } + } diff --git a/exercises/practice/scrabble-score/src/test/java/ScrabbleScoreTest.java b/exercises/practice/scrabble-score/src/test/java/ScrabbleScoreTest.java index 9fc05c0f5..7bb7e776d 100644 --- a/exercises/practice/scrabble-score/src/test/java/ScrabbleScoreTest.java +++ b/exercises/practice/scrabble-score/src/test/java/ScrabbleScoreTest.java @@ -8,89 +8,89 @@ public class ScrabbleScoreTest { @Test @DisplayName("lowercase letter") - public void testALowerCaseLetter() { - Scrabble scrabble = new Scrabble("a"); - assertThat(scrabble.getScore()).isEqualTo(1); + public void lowercaseLetter() { + assertThat(new Scrabble("a").getScore()) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("uppercase letter") - public void testAUpperCaseLetter() { - Scrabble scrabble = new Scrabble("A"); - assertThat(scrabble.getScore()).isEqualTo(1); + public void uppercaseLetter() { + assertThat(new Scrabble("A").getScore()) + .isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("valuable letter") - public void testAValuableLetter() { - Scrabble scrabble = new Scrabble("f"); - assertThat(scrabble.getScore()).isEqualTo(4); + public void valuableLetter() { + assertThat(new Scrabble("f").getScore()) + .isEqualTo(4); } @Disabled("Remove to run test") @Test @DisplayName("short word") - public void testAShortWord() { - Scrabble scrabble = new Scrabble("at"); - assertThat(scrabble.getScore()).isEqualTo(2); + public void shortWord() { + assertThat(new Scrabble("at").getScore()) + .isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("short, valuable word") - public void testAShortValuableWord() { - Scrabble scrabble = new Scrabble("zoo"); - assertThat(scrabble.getScore()).isEqualTo(12); + public void shortValuableWord() { + assertThat(new Scrabble("zoo").getScore()) + .isEqualTo(12); } @Disabled("Remove to run test") @Test @DisplayName("medium word") - public void testAMediumWord() { - Scrabble scrabble = new Scrabble("street"); - assertThat(scrabble.getScore()).isEqualTo(6); + public void mediumWord() { + assertThat(new Scrabble("street").getScore()) + .isEqualTo(6); } @Disabled("Remove to run test") @Test @DisplayName("medium, valuable word") - public void testAMediumValuableWord() { - Scrabble scrabble = new Scrabble("quirky"); - assertThat(scrabble.getScore()).isEqualTo(22); + public void mediumValuableWord() { + assertThat(new Scrabble("quirky").getScore()) + .isEqualTo(22); } @Disabled("Remove to run test") @Test @DisplayName("long, mixed-case word") - public void testALongMixCaseWord() { - Scrabble scrabble = new Scrabble("OxyphenButazone"); - assertThat(scrabble.getScore()).isEqualTo(41); + public void longMixedCaseWord() { + assertThat(new Scrabble("OxyphenButazone").getScore()) + .isEqualTo(41); } @Disabled("Remove to run test") @Test @DisplayName("english-like word") - public void testAEnglishLikeWord() { - Scrabble scrabble = new Scrabble("pinata"); - assertThat(scrabble.getScore()).isEqualTo(8); + public void englishLikeWord() { + assertThat(new Scrabble("pinata").getScore()) + .isEqualTo(8); } @Disabled("Remove to run test") @Test @DisplayName("empty input") - public void testAnEmptyInput() { - Scrabble scrabble = new Scrabble(""); - assertThat(scrabble.getScore()).isEqualTo(0); + public void emptyInput() { + assertThat(new Scrabble("").getScore()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("entire alphabet available") - public void testEntireAlphabetAvailable() { - Scrabble scrabble = new Scrabble("abcdefghijklmnopqrstuvwxyz"); - assertThat(scrabble.getScore()).isEqualTo(87); + public void entireAlphabetAvailable() { + assertThat(new Scrabble("abcdefghijklmnopqrstuvwxyz").getScore()) + .isEqualTo(87); } } diff --git a/exercises/practice/secret-handshake/src/test/java/HandshakeCalculatorTest.java b/exercises/practice/secret-handshake/src/test/java/HandshakeCalculatorTest.java index a1cc3ce32..156930671 100644 --- a/exercises/practice/secret-handshake/src/test/java/HandshakeCalculatorTest.java +++ b/exercises/practice/secret-handshake/src/test/java/HandshakeCalculatorTest.java @@ -6,114 +6,99 @@ public class HandshakeCalculatorTest { - private final HandshakeCalculator handshakeCalculator = new HandshakeCalculator(); - @Test @DisplayName("wink for 1") - public void testThatInput1YieldsAWink() { - assertThat(handshakeCalculator.calculateHandshake(1)).containsExactly(Signal.WINK); + public void winkFor1() { + assertThat(new HandshakeCalculator().calculateHandshake(1)) + .containsExactly(Signal.WINK); } @Disabled("Remove to run test") @Test @DisplayName("double blink for 10") - public void testThatInput2YieldsADoubleBlink() { - assertThat(handshakeCalculator.calculateHandshake(2)).containsExactly(Signal.DOUBLE_BLINK); + public void doubleBlinkFor10() { + assertThat(new HandshakeCalculator().calculateHandshake(2)) + .containsExactly(Signal.DOUBLE_BLINK); } @Disabled("Remove to run test") @Test @DisplayName("close your eyes for 100") - public void testThatInput4YieldsACloseYourEyes() { - assertThat(handshakeCalculator.calculateHandshake(4)).containsExactly(Signal.CLOSE_YOUR_EYES); + public void closeYourEyesFor100() { + assertThat(new HandshakeCalculator().calculateHandshake(4)) + .containsExactly(Signal.CLOSE_YOUR_EYES); } @Disabled("Remove to run test") @Test @DisplayName("jump for 1000") - public void testThatInput8YieldsAJump() { - assertThat(handshakeCalculator.calculateHandshake(8)).containsExactly(Signal.JUMP); + public void jumpFor1000() { + assertThat(new HandshakeCalculator().calculateHandshake(8)) + .containsExactly(Signal.JUMP); } @Disabled("Remove to run test") @Test @DisplayName("combine two actions") - public void testAnInputThatYieldsTwoActions() { - assertThat(handshakeCalculator.calculateHandshake(3)) + public void combineTwoActions() { + assertThat(new HandshakeCalculator().calculateHandshake(3)) .containsExactly(Signal.WINK, Signal.DOUBLE_BLINK); } @Disabled("Remove to run test") @Test @DisplayName("reverse two actions") - public void testAnInputThatYieldsTwoReversedActions() { - assertThat(handshakeCalculator.calculateHandshake(19)) + public void reverseTwoActions() { + assertThat(new HandshakeCalculator().calculateHandshake(19)) .containsExactly(Signal.DOUBLE_BLINK, Signal.WINK); } @Disabled("Remove to run test") @Test @DisplayName("reversing one action gives the same action") - public void testReversingASingleActionYieldsTheSameAction() { - assertThat(handshakeCalculator.calculateHandshake(24)).containsExactly(Signal.JUMP); + public void reversingOneActionGivesTheSameAction() { + assertThat(new HandshakeCalculator().calculateHandshake(24)) + .containsExactly(Signal.JUMP); } @Disabled("Remove to run test") @Test @DisplayName("reversing no actions still gives no actions") - public void testReversingNoActionsYieldsNoActions() { - assertThat(handshakeCalculator.calculateHandshake(16)).isEmpty(); + public void reversingNoActionsStillGivesNoActions() { + assertThat(new HandshakeCalculator().calculateHandshake(16)) + .isEmpty(); } @Disabled("Remove to run test") @Test @DisplayName("all possible actions") - public void testInputThatYieldsAllActions() { - assertThat(handshakeCalculator.calculateHandshake(15)) - .containsExactly(Signal.WINK, Signal.DOUBLE_BLINK, Signal.CLOSE_YOUR_EYES, Signal.JUMP); + public void allPossibleActions() { + assertThat(new HandshakeCalculator().calculateHandshake(15)) + .containsExactly( + Signal.WINK, + Signal.DOUBLE_BLINK, + Signal.CLOSE_YOUR_EYES, + Signal.JUMP); } @Disabled("Remove to run test") @Test @DisplayName("reverse all possible actions") - public void testInputThatYieldsAllActionsReversed() { - assertThat(handshakeCalculator.calculateHandshake(31)) - .containsExactly(Signal.JUMP, Signal.CLOSE_YOUR_EYES, Signal.DOUBLE_BLINK, Signal.WINK); + public void reverseAllPossibleActions() { + assertThat(new HandshakeCalculator().calculateHandshake(31)) + .containsExactly( + Signal.JUMP, + Signal.CLOSE_YOUR_EYES, + Signal.DOUBLE_BLINK, + Signal.WINK); } @Disabled("Remove to run test") @Test @DisplayName("do nothing for zero") - public void testThatInput0YieldsNoActions() { - assertThat(handshakeCalculator.calculateHandshake(0)).isEmpty(); - } - - /* The following tests diverge from the canonical test data to test numbers with binary representation with - * more than five digits are correctly handled. For more details, check out issue #1965 here: - * (https://github.com/exercism/java/issues/1965). - */ - @Disabled("Remove to run test") - @Test - @DisplayName("handles input with more than five bits with reversal") - public void testThatHandlesMoreThanFiveBinaryPlacesWithReversal() { - assertThat(handshakeCalculator.calculateHandshake(51)) - .containsExactly(Signal.DOUBLE_BLINK, Signal.WINK); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("handles input with more than five bits without reversal") - public void testThatHandlesMoreThanFiveBinaryPlacesWithoutReversal() { - assertThat(handshakeCalculator.calculateHandshake(35)) - .containsExactly(Signal.WINK, Signal.DOUBLE_BLINK); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("all actions for input with more than five bits") - public void testInputThatYieldsAllActionsFromMoreThanFiveBinaryPlaces() { - assertThat(handshakeCalculator.calculateHandshake(111)) - .containsExactly(Signal.WINK, Signal.DOUBLE_BLINK, Signal.CLOSE_YOUR_EYES, Signal.JUMP); + public void doNothingForZero() { + assertThat(new HandshakeCalculator().calculateHandshake(0)) + .isEmpty(); } } diff --git a/exercises/practice/series/src/test/java/SeriesTest.java b/exercises/practice/series/src/test/java/SeriesTest.java index 726e9fd24..4cf61d43c 100644 --- a/exercises/practice/series/src/test/java/SeriesTest.java +++ b/exercises/practice/series/src/test/java/SeriesTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -14,125 +12,99 @@ public class SeriesTest { @Test @DisplayName("slices of one from one") public void slicesOfOneFromOne() { - Series series = new Series("1"); - List expected = Collections.singletonList("1"); - List actual = series.slices(1); - assertThat(actual).isEqualTo(expected); + assertThat(new Series("1").slices(1)) + .isEqualTo(List.of("1")); } @Disabled("Remove to run test") @Test @DisplayName("slices of one from two") public void slicesOfOneFromTwo() { - Series series = new Series("12"); - List expected = Arrays.asList("1", "2"); - List actual = series.slices(1); - assertThat(actual).isEqualTo(expected); + assertThat(new Series("12").slices(1)) + .isEqualTo(List.of("1", "2")); } @Disabled("Remove to run test") @Test @DisplayName("slices of two") public void slicesOfTwo() { - Series series = new Series("35"); - List expected = Collections.singletonList("35"); - List actual = series.slices(2); - assertThat(actual).isEqualTo(expected); + assertThat(new Series("35").slices(2)) + .isEqualTo(List.of("35")); } @Disabled("Remove to run test") @Test @DisplayName("slices of two overlap") public void slicesOfTwoOverlap() { - Series series = new Series("9142"); - List expected = Arrays.asList("91", "14", "42"); - List actual = series.slices(2); - assertThat(actual).isEqualTo(expected); + assertThat(new Series("9142").slices(2)) + .isEqualTo(List.of("91", "14", "42")); } @Disabled("Remove to run test") @Test @DisplayName("slices can include duplicates") - public void slicesIncludeDuplicates() { - Series series = new Series("777777"); - List expected = Arrays.asList( - "777", - "777", - "777", - "777" - ); - List actual = series.slices(3); - assertThat(actual).isEqualTo(expected); + public void slicesCanIncludeDuplicates() { + assertThat(new Series("777777").slices(3)) + .isEqualTo(List.of("777", "777", "777", "777")); } @Disabled("Remove to run test") @Test @DisplayName("slices of a long series") - public void slicesOfLongSeries() { - Series series = new Series("918493904243"); - List expected = Arrays.asList( - "91849", - "18493", - "84939", - "49390", - "93904", - "39042", - "90424", - "04243" - ); - List actual = series.slices(5); - assertThat(actual).isEqualTo(expected); + public void slicesOfALongSeries() { + assertThat(new Series("918493904243").slices(5)) + .isEqualTo(List.of( + "91849", + "18493", + "84939", + "49390", + "93904", + "39042", + "90424", + "04243" + )); } @Disabled("Remove to run test") @Test @DisplayName("slice length is too large") - public void sliceLengthIsToolarge() { - Series series = new Series("12345"); - + public void sliceLengthIsTooLarge() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> series.slices(6)) + .isThrownBy(() -> new Series("12345").slices(6)) .withMessage("slice length cannot be greater than series length"); } @Disabled("Remove to run test") @Test @DisplayName("slice length is way too large") - public void sliceLengthIsWayToolarge() { - Series series = new Series("12345"); - + public void sliceLengthIsWayTooLarge() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> series.slices(42)) + .isThrownBy(() -> new Series("12345").slices(42)) .withMessage("slice length cannot be greater than series length"); } @Disabled("Remove to run test") @Test @DisplayName("slice length cannot be zero") - public void sliceLengthZero() { - Series series = new Series("12345"); - + public void sliceLengthCannotBeZero() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> series.slices(0)) + .isThrownBy(() -> new Series("12345").slices(0)) .withMessage("slice length cannot be negative or zero"); } @Disabled("Remove to run test") @Test @DisplayName("slice length cannot be negative") - public void sliceLengthNegative() { - Series series = new Series("123"); - + public void sliceLengthCannotBeNegative() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> series.slices(-1)) + .isThrownBy(() -> new Series("123").slices(-1)) .withMessage("slice length cannot be negative or zero"); } @Disabled("Remove to run test") @Test @DisplayName("empty series is invalid") - public void emptySeries() { - + public void emptySeriesIsInvalid() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Series("")) .withMessage("series cannot be empty"); diff --git a/exercises/practice/sgf-parsing/src/test/java/SgfParsingTest.java b/exercises/practice/sgf-parsing/src/test/java/SgfParsingTest.java index afd458506..fab282161 100644 --- a/exercises/practice/sgf-parsing/src/test/java/SgfParsingTest.java +++ b/exercises/practice/sgf-parsing/src/test/java/SgfParsingTest.java @@ -1,258 +1,234 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class SgfParsingTest { @Test @DisplayName("empty input") - public void emptyInput() { - String input = ""; - assertThatExceptionOfType(SgfParsingException.class).as("tree missing") - .isThrownBy(() -> new SgfParsing().parse(input)); + public void emptyInput() throws SgfParsingException { + assertThatExceptionOfType(SgfParsingException.class) + .isThrownBy(() -> new SgfParsing().parse("")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("tree with no nodes") - public void treeWithNoNodes() { - String input = "()"; + public void treeWithNoNodes() throws SgfParsingException { assertThatExceptionOfType(SgfParsingException.class) - .as("tree with no nodes") - .isThrownBy(() -> new SgfParsing().parse(input)); + .isThrownBy(() -> new SgfParsing().parse("()")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("node without tree") - public void nodeWithoutTree() { - String input = ";"; - assertThatExceptionOfType(SgfParsingException.class).as("tree missing") - .isThrownBy(() -> new SgfParsing().parse(input)); + public void nodeWithoutTree() throws SgfParsingException { + assertThatExceptionOfType(SgfParsingException.class) + .isThrownBy(() -> new SgfParsing().parse(";")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("node without properties") public void nodeWithoutProperties() throws SgfParsingException { - String input = "(;)"; SgfNode expected = new SgfNode(); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;)")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("single node tree") public void singleNodeTree() throws SgfParsingException { - String input = "(;A[B])"; SgfNode expected = new SgfNode(Map.of("A", List.of("B"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[B])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("multiple properties") public void multipleProperties() throws SgfParsingException { - String input = "(;A[b]C[d])"; - SgfNode expected = new SgfNode(Map.of("A", List.of("b"), - "C", List.of("d"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + SgfNode expected = new SgfNode(Map.of( + "A", List.of("b"), + "C", List.of("d") + )); + assertThat(new SgfParsing().parse("(;A[b]C[d])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("properties without delimiter") - public void propertiesWithoutDelimiter() { - String input = "(;A)"; - assertThatExceptionOfType(SgfParsingException.class).as("properties without delimiter") - .isThrownBy(() -> new SgfParsing().parse(input)); + public void propertiesWithoutDelimiter() throws SgfParsingException { + assertThatExceptionOfType(SgfParsingException.class) + .isThrownBy(() -> new SgfParsing().parse("(;A)")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("all lowercase property") - public void allLowercaseProperty() { - String input = "(;a[b])"; - assertThatExceptionOfType(SgfParsingException.class).as("property must be in uppercase") - .isThrownBy(() -> new SgfParsing().parse(input)); + public void allLowercaseProperty() throws SgfParsingException { + assertThatExceptionOfType(SgfParsingException.class) + .isThrownBy(() -> new SgfParsing().parse("(;a[b])")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("upper and lowercase property") - public void upperAndLowercaseProperty() { - String input = "(;Aa[b])"; - assertThatExceptionOfType(SgfParsingException.class).as("property must be in uppercase") - .isThrownBy(() -> new SgfParsing().parse(input)); + public void upperAndLowercaseProperty() throws SgfParsingException { + assertThatExceptionOfType(SgfParsingException.class) + .isThrownBy(() -> new SgfParsing().parse("(;Aa[b])")); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("two nodes") public void twoNodes() throws SgfParsingException { - String input = "(;A[B];B[C])"; - SgfNode expected = new SgfNode(Map.of("A", List.of("B")), + SgfNode expected = new SgfNode( + Map.of("A", List.of("B")), List.of( new SgfNode(Map.of("B", List.of("C"))) - )); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + ) + ); + assertThat(new SgfParsing().parse("(;A[B];B[C])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("two child trees") public void twoChildTrees() throws SgfParsingException { - String input = "(;A[B](;B[C])(;C[D]))"; - SgfNode expected = new SgfNode(Map.of("A", List.of("B")), + SgfNode expected = new SgfNode( + Map.of("A", List.of("B")), List.of( new SgfNode(Map.of("B", List.of("C"))), new SgfNode(Map.of("C", List.of("D"))) - )); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + ) + ); + assertThat(new SgfParsing().parse("(;A[B](;B[C])(;C[D]))")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("multiple property values") public void multiplePropertyValues() throws SgfParsingException { - String input = "(;A[b][c][d])"; SgfNode expected = new SgfNode(Map.of("A", List.of("b", "c", "d"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[b][c][d])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("within property values, whitespace characters such as tab are converted to spaces") - public void withinPropertyValueWhitespace() throws SgfParsingException { - String input = "(;A[hello\t\tworld])"; + public void withinPropertyValuesWhitespaceCharactersSuchAsTabAreConvertedToSp() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("hello world"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[hello\t\tworld])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("within property values, newlines remain as newlines") - public void withinPropertyValueNewline() throws SgfParsingException { - String input = "(;A[hello\n\nworld])"; + public void withinPropertyValuesNewlinesRemainAsNewlines() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("hello\n\nworld"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[hello\n\nworld])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("escaped closing bracket within property value becomes just a closing bracket") - public void escapedClosingBracket() throws SgfParsingException { - String input = "(;A[\\]])"; + public void escapedClosingBracketWithinPropertyValueBecomesJustAClosingBracke() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("]"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[\\]])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("escaped backslash in property value becomes just a backslash") - public void escapedBacklash() throws SgfParsingException { - String input = "(;A[\\\\])"; + public void escapedBackslashInPropertyValueBecomesJustABackslash() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("\\"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[\\\\])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("opening bracket within property value doesn't need to be escaped") - public void openingBracketNeedNotToBeEscaped() throws SgfParsingException { - String input = "(;A[x[y\\]z][foo]B[bar];C[baz])"; - SgfNode expected = new SgfNode(Map.of("A", List.of("x[y]z", "foo"), - "B", List.of("bar")), + public void openingBracketWithinPropertyValueDoesnTNeedToBeEscaped() throws SgfParsingException { + SgfNode expected = new SgfNode( + Map.of( + "A", List.of("x[y]z", "foo"), + "B", List.of("bar") + ), List.of( new SgfNode(Map.of("C", List.of("baz"))) - )); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + ) + ); + assertThat(new SgfParsing().parse("(;A[x[y\\]z][foo]B[bar];C[baz])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("semicolon in property value doesn't need to be escaped") - public void semicolonNeedNotToBeEscaped() throws SgfParsingException { - String input = "(;A[a;b][foo]B[bar];C[baz])"; - SgfNode expected = new SgfNode(Map.of("A", List.of("a;b", "foo"), - "B", List.of("bar")), + public void semicolonInPropertyValueDoesnTNeedToBeEscaped() throws SgfParsingException { + SgfNode expected = new SgfNode( + Map.of( + "A", List.of("a;b", "foo"), + "B", List.of("bar") + ), List.of( new SgfNode(Map.of("C", List.of("baz"))) - )); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + ) + ); + assertThat(new SgfParsing().parse("(;A[a;b][foo]B[bar];C[baz])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("parentheses in property value don't need to be escaped") - public void paranthesesNeedNotToBeEscaped() throws SgfParsingException { - String input = "(;A[x(y)z][foo]B[bar];C[baz])"; - SgfNode expected = new SgfNode(Map.of("A", List.of("x(y)z", "foo"), - "B", List.of("bar")), + public void parenthesesInPropertyValueDonTNeedToBeEscaped() throws SgfParsingException { + SgfNode expected = new SgfNode( + Map.of( + "A", List.of("x(y)z", "foo"), + "B", List.of("bar") + ), List.of( new SgfNode(Map.of("C", List.of("baz"))) - )); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + ) + ); + assertThat(new SgfParsing().parse("(;A[x(y)z][foo]B[bar];C[baz])")).isEqualTo(expected); } - @Test @Disabled("Remove to run test") + @Test @DisplayName("escaped tab in property value is converted to space") - public void escapedTab() throws SgfParsingException { - String input = "(;A[hello\\\tworld])"; + public void escapedTabInPropertyValueIsConvertedToSpace() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("hello world"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[hello\\\tworld])")).isEqualTo(expected); } - - @Test + @Disabled("Remove to run test") + @Test @DisplayName("escaped newline in property value is converted to nothing at all") - public void escapedNewline() throws SgfParsingException { - String input = "(;A[hello\\\nworld])"; + public void escapedNewlineInPropertyValueIsConvertedToNothingAtAll() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("helloworld"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[hello\\\nworld])")).isEqualTo(expected); } - - @Test @Disabled("Remove to run test") + @Test @DisplayName("escaped t and n in property value are just letters, not whitespace") - public void escapedTAndN() throws SgfParsingException { - String input = "(;A[\\t = t and \\n = n])"; + public void escapedTAndNInPropertyValueAreJustLettersNotWhitespace() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("t = t and n = n"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[\\t = t and \\n = n])")).isEqualTo(expected); } - - @Test @Disabled("Remove to run test") + @Test @DisplayName("mixing various kinds of whitespace and escaped characters in property value") - public void mixOfEscapedCharactersAndWhitespaces() throws SgfParsingException { - String input = "(;A[\\]b\nc\\\nd\t\te\\\\ \\\n\\]])"; + public void mixingVariousKindsOfWhitespaceAndEscapedCharactersInPropertyValue() throws SgfParsingException { SgfNode expected = new SgfNode(Map.of("A", List.of("]b\ncd e\\ ]"))); - SgfNode actual = new SgfParsing().parse(input); - assertThat(actual).isEqualTo(expected); + assertThat(new SgfParsing().parse("(;A[\\]b\nc\\\nd\t\te\\\\ \\\n\\]])")).isEqualTo(expected); } + } diff --git a/exercises/practice/sieve/src/test/java/SieveTest.java b/exercises/practice/sieve/src/test/java/SieveTest.java index 529329323..a904042ec 100644 --- a/exercises/practice/sieve/src/test/java/SieveTest.java +++ b/exercises/practice/sieve/src/test/java/SieveTest.java @@ -2,8 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -12,58 +10,210 @@ public class SieveTest { @Test @DisplayName("no primes under two") - public void noPrimesUnder2() { - Sieve sieve = new Sieve(1); - List expectedOutput = Collections.emptyList(); - - assertThat(sieve.getPrimes()).isEqualTo(expectedOutput); + public void noPrimesUnderTwo() { + assertThat(new Sieve(1).getPrimes()) + .isEqualTo(List.of()); } @Disabled("Remove to run test") @Test @DisplayName("find first prime") public void findFirstPrime() { - Sieve sieve = new Sieve(2); - List expectedOutput = Collections.singletonList(2); - - assertThat(sieve.getPrimes()).isEqualTo(expectedOutput); + assertThat(new Sieve(2).getPrimes()) + .isEqualTo(List.of(2)); } @Disabled("Remove to run test") @Test @DisplayName("find primes up to 10") public void findPrimesUpTo10() { - Sieve sieve = new Sieve(10); - List expectedOutput = Arrays.asList(2, 3, 5, 7); - - assertThat(sieve.getPrimes()).isEqualTo(expectedOutput); + assertThat(new Sieve(10).getPrimes()) + .isEqualTo(List.of(2, 3, 5, 7)); } @Disabled("Remove to run test") @Test @DisplayName("limit is prime") public void limitIsPrime() { - Sieve sieve = new Sieve(13); - List expectedOutput = Arrays.asList(2, 3, 5, 7, 11, 13); - - assertThat(sieve.getPrimes()).isEqualTo(expectedOutput); + assertThat(new Sieve(13).getPrimes()) + .isEqualTo(List.of(2, 3, 5, 7, 11, 13)); } @Disabled("Remove to run test") @Test @DisplayName("find primes up to 1000") public void findPrimesUpTo1000() { - Sieve sieve = new Sieve(1000); - List expectedOutput = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, - 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, - 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, - 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, - 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, - 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, - 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, - 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997); - - assertThat(sieve.getPrimes()).isEqualTo(expectedOutput); + assertThat(new Sieve(1000).getPrimes()) + .isEqualTo(List.of( + 2, + 3, + 5, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 53, + 59, + 61, + 67, + 71, + 73, + 79, + 83, + 89, + 97, + 101, + 103, + 107, + 109, + 113, + 127, + 131, + 137, + 139, + 149, + 151, + 157, + 163, + 167, + 173, + 179, + 181, + 191, + 193, + 197, + 199, + 211, + 223, + 227, + 229, + 233, + 239, + 241, + 251, + 257, + 263, + 269, + 271, + 277, + 281, + 283, + 293, + 307, + 311, + 313, + 317, + 331, + 337, + 347, + 349, + 353, + 359, + 367, + 373, + 379, + 383, + 389, + 397, + 401, + 409, + 419, + 421, + 431, + 433, + 439, + 443, + 449, + 457, + 461, + 463, + 467, + 479, + 487, + 491, + 499, + 503, + 509, + 521, + 523, + 541, + 547, + 557, + 563, + 569, + 571, + 577, + 587, + 593, + 599, + 601, + 607, + 613, + 617, + 619, + 631, + 641, + 643, + 647, + 653, + 659, + 661, + 673, + 677, + 683, + 691, + 701, + 709, + 719, + 727, + 733, + 739, + 743, + 751, + 757, + 761, + 769, + 773, + 787, + 797, + 809, + 811, + 821, + 823, + 827, + 829, + 839, + 853, + 857, + 859, + 863, + 877, + 881, + 883, + 887, + 907, + 911, + 919, + 929, + 937, + 941, + 947, + 953, + 967, + 971, + 977, + 983, + 991, + 997 + )); } + } diff --git a/exercises/practice/simple-linked-list/src/test/java/SimpleLinkedListTest.java b/exercises/practice/simple-linked-list/src/test/java/SimpleLinkedListTest.java index c885893d3..3aeaa65af 100644 --- a/exercises/practice/simple-linked-list/src/test/java/SimpleLinkedListTest.java +++ b/exercises/practice/simple-linked-list/src/test/java/SimpleLinkedListTest.java @@ -1,7 +1,9 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; + import java.util.NoSuchElementException; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -33,7 +35,7 @@ public void countNonEmptyListHasCorrectLength() { @Disabled("Remove to run test") @Test @DisplayName("pop -> Pop from empty list is an error") - public void popFromEmptyListIsAnError() { + public void popPopFromEmptyListIsAnError() { SimpleLinkedList list = new SimpleLinkedList<>(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(list::pop); } @@ -41,7 +43,7 @@ public void popFromEmptyListIsAnError() { @Disabled("Remove to run test") @Test @DisplayName("pop -> Can pop from singleton list") - public void canPopFromSingletonList() { + public void popCanPopFromSingletonList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1}); assertThat(list.pop()).isEqualTo(1); } @@ -49,7 +51,7 @@ public void canPopFromSingletonList() { @Disabled("Remove to run test") @Test @DisplayName("pop -> Can pop from non-empty list") - public void canPopFromNonEmptyList() { + public void popCanPopFromNonEmptyList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); assertThat(list.pop()).isEqualTo(2); } @@ -57,7 +59,7 @@ public void canPopFromNonEmptyList() { @Disabled("Remove to run test") @Test @DisplayName("pop -> Can pop multiple items") - public void canPopMultipleItems() { + public void popCanPopMultipleItems() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); assertThat(list.pop()).isEqualTo(2); assertThat(list.pop()).isEqualTo(1); @@ -66,7 +68,7 @@ public void canPopMultipleItems() { @Disabled("Remove to run test") @Test @DisplayName("pop -> Pop updates the count") - public void popUpdatesTheCount() { + public void popPopUpdatesTheCount() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); assertThat(list.size()).isEqualTo(2); assertThat(list.pop()).isEqualTo(2); @@ -78,25 +80,23 @@ public void popUpdatesTheCount() { @Disabled("Remove to run test") @Test @DisplayName("push -> Can push to an empty list") - public void canPushToAnEmptyList() { + public void pushCanPushToAnEmptyList() { SimpleLinkedList list = new SimpleLinkedList<>(); list.push(1); - assertThat(list.size()).isEqualTo(1); } @Disabled("Remove to run test") @Test @DisplayName("push -> Can push to a non-empty list") - public void canPushToANonEmptyList() { + public void pushCanPushToANonEmptyList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); list.push(3); - assertThat(list.size()).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("push -> Push updates count") - public void pushUpdatesCount() { + public void pushPushUpdatesCount() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); list.push(3); assertThat(list.size()).isEqualTo(3); @@ -105,7 +105,7 @@ public void pushUpdatesCount() { @Disabled("Remove to run test") @Test @DisplayName("push -> Push and pop") - public void pushAndPop() { + public void pushPushAndPop() { SimpleLinkedList list = new SimpleLinkedList<>(); list.push(1); list.push(2); @@ -120,7 +120,7 @@ public void pushAndPop() { @Disabled("Remove to run test") @Test @DisplayName("peek -> Peek on empty list is an error") - public void peekOnEmptyListIsAnError() { + public void peekPeekOnEmptyListIsAnError() { SimpleLinkedList list = new SimpleLinkedList<>(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(list::peek); } @@ -128,7 +128,7 @@ public void peekOnEmptyListIsAnError() { @Disabled("Remove to run test") @Test @DisplayName("peek -> Can peek on singleton list") - public void canPeekOnSingletonList() { + public void peekCanPeekOnSingletonList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1}); assertThat(list.peek()).isEqualTo(1); } @@ -136,7 +136,7 @@ public void canPeekOnSingletonList() { @Disabled("Remove to run test") @Test @DisplayName("peek -> Can peek on non-empty list") - public void canPeekOnNonEmptyList() { + public void peekCanPeekOnNonEmptyList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); assertThat(list.peek()).isEqualTo(2); } @@ -144,7 +144,7 @@ public void canPeekOnNonEmptyList() { @Disabled("Remove to run test") @Test @DisplayName("peek -> Peek does not change the count") - public void peekDoesNotChangeTheCount() { + public void peekPeekDoesNotChangeTheCount() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2}); assertThat(list.peek()).isEqualTo(2); assertThat(list.size()).isEqualTo(2); @@ -153,7 +153,7 @@ public void peekDoesNotChangeTheCount() { @Disabled("Remove to run test") @Test @DisplayName("peek -> Can peek after a pop and push") - public void canPeekAfterAPopAndPush() { + public void peekCanPeekAfterAPopAndPush() { SimpleLinkedList list = new SimpleLinkedList<>(); list.push(1); list.push(2); @@ -167,7 +167,7 @@ public void canPeekAfterAPopAndPush() { @Disabled("Remove to run test") @Test @DisplayName("toList LIFO -> Empty linked list to list is empty") - public void toListLifoEmptyLinkedListToListIsEmpty() { + public void tolistLifoEmptyLinkedListToListIsEmpty() { SimpleLinkedList list = new SimpleLinkedList<>(); assertThat(list.toList()).isEmpty(); } @@ -175,7 +175,7 @@ public void toListLifoEmptyLinkedListToListIsEmpty() { @Disabled("Remove to run test") @Test @DisplayName("toList LIFO -> To list with multiple values") - public void toListLifoToListWithMultipleValues() { + public void tolistLifoToListWithMultipleValues() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2, 3}); assertThat(list.toList()).containsExactly(3, 2, 1); } @@ -183,7 +183,7 @@ public void toListLifoToListWithMultipleValues() { @Disabled("Remove to run test") @Test @DisplayName("toList LIFO -> To list after a pop") - public void toListLifoToListAfterAPop() { + public void tolistLifoToListAfterAPop() { SimpleLinkedList list = new SimpleLinkedList<>(); list.push(1); list.push(2); @@ -196,7 +196,7 @@ public void toListLifoToListAfterAPop() { @Disabled("Remove to run test") @Test @DisplayName("reverse -> Reversed empty list has same values") - public void reversedEmptyListHasSameValues() { + public void reverseReversedEmptyListHasSameValues() { SimpleLinkedList list = new SimpleLinkedList<>(); list.reverse(); assertThat(list.toList()).isEmpty(); @@ -205,7 +205,7 @@ public void reversedEmptyListHasSameValues() { @Disabled("Remove to run test") @Test @DisplayName("reverse -> Reversed singleton list is same list") - public void reversedSingletonListIsSameList() { + public void reverseReversedSingletonListIsSameList() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1}); list.reverse(); assertThat(list.toList()).containsExactly(1); @@ -214,7 +214,7 @@ public void reversedSingletonListIsSameList() { @Disabled("Remove to run test") @Test @DisplayName("reverse -> Reversed non-empty list is reversed") - public void reversedNonEmptyListIsReversed() { + public void reverseReversedNonEmptyListIsReversed() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2, 3}); list.reverse(); assertThat(list.size()).isEqualTo(3); @@ -226,7 +226,7 @@ public void reversedNonEmptyListIsReversed() { @Disabled("Remove to run test") @Test @DisplayName("reverse -> Double reverse") - public void doubleReverse() { + public void reverseDoubleReverse() { SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{1, 2, 3}); list.reverse(); list.reverse(); @@ -235,12 +235,4 @@ public void doubleReverse() { assertThat(list.pop()).isEqualTo(1); } - @Disabled("Remove to run test") - @Test - @DisplayName("Create list from array") - public void canCreateFromArray() { - Character[] values = new Character[]{'1', '2', '3'}; - SimpleLinkedList list = new SimpleLinkedList(values); - assertThat(list.size()).isEqualTo(3); - } } diff --git a/exercises/practice/space-age/src/test/java/SpaceAgeTest.java b/exercises/practice/space-age/src/test/java/SpaceAgeTest.java index 248d6938e..7c6355d8c 100644 --- a/exercises/practice/space-age/src/test/java/SpaceAgeTest.java +++ b/exercises/practice/space-age/src/test/java/SpaceAgeTest.java @@ -12,71 +12,64 @@ public class SpaceAgeTest { @Test @DisplayName("age on Earth") public void ageOnEarth() { - SpaceAge age = new SpaceAge(1000000000); - - assertThat(age.onEarth()).isEqualTo(31.69, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(1000000000L).onEarth()) + .isEqualTo(31.69, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Mercury") public void ageOnMercury() { - SpaceAge age = new SpaceAge(2134835688); - - assertThat(age.onMercury()).isEqualTo(280.88, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(2134835688L).onMercury()) + .isEqualTo(280.88, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Venus") public void ageOnVenus() { - SpaceAge age = new SpaceAge(189839836); - - assertThat(age.onVenus()).isEqualTo(9.78, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(189839836L).onVenus()) + .isEqualTo(9.78, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Mars") public void ageOnMars() { - SpaceAge age = new SpaceAge(2129871239L); - - assertThat(age.onMars()).isEqualTo(35.88, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(2129871239L).onMars()) + .isEqualTo(35.88, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Jupiter") public void ageOnJupiter() { - SpaceAge age = new SpaceAge(901876382); - - assertThat(age.onJupiter()).isEqualTo(2.41, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(901876382L).onJupiter()) + .isEqualTo(2.41, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Saturn") public void ageOnSaturn() { - SpaceAge age = new SpaceAge(2000000000L); - - assertThat(age.onSaturn()).isEqualTo(2.15, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(2000000000L).onSaturn()) + .isEqualTo(2.15, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Uranus") public void ageOnUranus() { - SpaceAge age = new SpaceAge(1210123456L); - - assertThat(age.onUranus()).isEqualTo(0.46, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(1210123456L).onUranus()) + .isEqualTo(0.46, offset(MAXIMUM_DELTA)); } @Disabled("Remove to run test") @Test @DisplayName("age on Neptune") public void ageOnNeptune() { - SpaceAge age = new SpaceAge(1821023456L); - - assertThat(age.onNeptune()).isEqualTo(0.35, offset(MAXIMUM_DELTA)); + assertThat(new SpaceAge(1821023456L).onNeptune()) + .isEqualTo(0.35, offset(MAXIMUM_DELTA)); } + } diff --git a/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java b/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java index 215afdc10..11d5e435f 100644 --- a/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java +++ b/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java @@ -16,73 +16,71 @@ public void setUp() { @Test @DisplayName("empty spiral") - public void testEmptySpiral() { + public void emptySpiral() { + assertThat(spiralMatrixBuilder.buildMatrixOfSize(0)).isEmpty(); + } @Disabled("Remove to run test") @Test @DisplayName("trivial spiral") - public void testTrivialSpiral() { - int[][] expected = { - {1} - }; + public void trivialSpiral() { + + int[][] expected = new int[][]{{1}}; + assertThat(spiralMatrixBuilder.buildMatrixOfSize(1)).isDeepEqualTo(expected); - assertThat(spiralMatrixBuilder.buildMatrixOfSize(1)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 2") - public void testSpiralOfSize2() { - int[][] expected = { - {1, 2}, - {4, 3} - }; + public void spiralOfSize2() { + + int[][] expected = new int[][]{{1, 2}, {4, 3}}; + assertThat(spiralMatrixBuilder.buildMatrixOfSize(2)).isDeepEqualTo(expected); - assertThat(spiralMatrixBuilder.buildMatrixOfSize(2)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 3") - public void testSpiralOfSize3() { - int[][] expected = { - {1, 2, 3}, - {8, 9, 4}, - {7, 6, 5} - }; + public void spiralOfSize3() { + + int[][] expected = new int[][]{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; + assertThat(spiralMatrixBuilder.buildMatrixOfSize(3)).isDeepEqualTo(expected); - assertThat(spiralMatrixBuilder.buildMatrixOfSize(3)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 4") - public void testSpiralOfSize4() { - int[][] expected = { - { 1, 2, 3, 4}, - {12, 13, 14, 5}, - {11, 16, 15, 6}, - {10, 9, 8, 7} + public void spiralOfSize4() { + + int[][] expected = new int[][]{ + {1, 2, 3, 4}, + {12, 13, 14, 5}, + {11, 16, 15, 6}, + {10, 9, 8, 7} }; + assertThat(spiralMatrixBuilder.buildMatrixOfSize(4)).isDeepEqualTo(expected); - assertThat(spiralMatrixBuilder.buildMatrixOfSize(4)).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 5") - public void testSpiralOfSize5() { - int[][] expected = { - { 1, 2, 3, 4, 5}, - {16, 17, 18, 19, 6}, - {15, 24, 25, 20, 7}, - {14, 23, 22, 21, 8}, - {13, 12, 11, 10, 9} + public void spiralOfSize5() { + + int[][] expected = new int[][]{ + {1, 2, 3, 4, 5}, + {16, 17, 18, 19, 6}, + {15, 24, 25, 20, 7}, + {14, 23, 22, 21, 8}, + {13, 12, 11, 10, 9} }; + assertThat(spiralMatrixBuilder.buildMatrixOfSize(5)).isDeepEqualTo(expected); - assertThat(spiralMatrixBuilder.buildMatrixOfSize(5)).isEqualTo(expected); } } diff --git a/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java b/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java index 1f54a9907..9ebd7b99c 100644 --- a/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java +++ b/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class SplitSecondStopwatchTest { + @Test @DisplayName("new stopwatch starts in ready state") public void newStopwatchStartsInReadyState() { @@ -16,7 +17,7 @@ public void newStopwatchStartsInReadyState() { @Disabled("Remove to run test") @Test @DisplayName("new stopwatch's current lap has no elapsed time") - public void newStopwatchCurrentLapHasNoElapsedTime() { + public void newStopwatchSCurrentLapHasNoElapsedTime() { SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); assertThat(stopwatch.currentLap()).isEqualTo("00:00:00"); } @@ -24,7 +25,7 @@ public void newStopwatchCurrentLapHasNoElapsedTime() { @Disabled("Remove to run test") @Test @DisplayName("new stopwatch's total has no elapsed time") - public void newStopwatchTotalHasNoElapsedTime() { + public void newStopwatchSTotalHasNoElapsedTime() { SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); assertThat(stopwatch.total()).isEqualTo("00:00:00"); } @@ -336,4 +337,5 @@ public void supportsVeryLongLaps() { stopwatch.lap(); assertThat(stopwatch.previousLaps()).containsExactly("01:23:45", "04:01:40", "08:43:05"); } + } diff --git a/exercises/practice/square-root/src/test/java/SquareRootTest.java b/exercises/practice/square-root/src/test/java/SquareRootTest.java index b5076e172..4a484c6c1 100644 --- a/exercises/practice/square-root/src/test/java/SquareRootTest.java +++ b/exercises/practice/square-root/src/test/java/SquareRootTest.java @@ -5,50 +5,52 @@ import static org.assertj.core.api.Assertions.assertThat; public class SquareRootTest { + @Test - @DisplayName("Square root of 1") - public void squareRootOf1() { + @DisplayName("root of 1") + public void rootOf1() { assertThat(new SquareRoot().squareRoot(1)) .isEqualTo(1); } @Disabled("Remove to run test") @Test - @DisplayName("Square root of 4") - public void squareRootOf4() { + @DisplayName("root of 4") + public void rootOf4() { assertThat(new SquareRoot().squareRoot(4)) .isEqualTo(2); } @Disabled("Remove to run test") @Test - @DisplayName("Square root of 25") - public void squareRootOf25() { + @DisplayName("root of 25") + public void rootOf25() { assertThat(new SquareRoot().squareRoot(25)) .isEqualTo(5); } @Disabled("Remove to run test") @Test - @DisplayName("Square root of 81") - public void squareRootOf81() { + @DisplayName("root of 81") + public void rootOf81() { assertThat(new SquareRoot().squareRoot(81)) .isEqualTo(9); } @Disabled("Remove to run test") @Test - @DisplayName("Square root of 196") - public void squareRootOf196() { + @DisplayName("root of 196") + public void rootOf196() { assertThat(new SquareRoot().squareRoot(196)) .isEqualTo(14); } @Disabled("Remove to run test") @Test - @DisplayName("Square root of 65025") - public void squareRootOf65025() { + @DisplayName("root of 65025") + public void rootOf65025() { assertThat(new SquareRoot().squareRoot(65025)) .isEqualTo(255); } + } diff --git a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java index 5ae93502b..c3bbc964f 100644 --- a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java +++ b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,299 +6,280 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class StateOfTicTacToeTest { - private StateOfTicTacToe stateOfTicTacToe; - @BeforeEach - public void setup() { - stateOfTicTacToe = new StateOfTicTacToe(); - } - - @Test - @DisplayName("Finished game where X won via left column victory") - public void testFinishedGameWhereXWonViaLeftColumnVictory() { + private StateOfTicTacToe stateOfTicTacToe = new StateOfTicTacToe(); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOO", "X ", "X "}) - ).isEqualTo(GameState.WIN); - } - - @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via middle column victory") - public void testFinishedGameWhereXWonViaMiddleColumnVictory() { + @DisplayName("Won games -> Finished game where X won via left column victory") + public void wonGamesFinishedGameWhereXWonViaLeftColumnVictory() { - assertThat( - stateOfTicTacToe.determineState(new String[]{"OXO", " X ", " X "}) - ).isEqualTo(GameState.WIN); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("Finished game where X won via right column victory") - public void testFinishedGameWhereXWonViaRightColumnVictory() { + assertThat(stateOfTicTacToe.determineState(new String[]{"XOO", "X ", "X "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"OOX", " X", " X"}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via left column victory") - public void testFinishedGameWhereOWonViaLeftColumnVictory() { + @DisplayName("Won games -> Finished game where X won via middle column victory") + public void wonGamesFinishedGameWhereXWonViaMiddleColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"OXO", " X ", " X "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"OXX", "OX ", "O "}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via middle column victory") - public void testFinishedGameWhereOWonViaMiddleColumnVictory() { + @DisplayName("Won games -> Finished game where X won via right column victory") + public void wonGamesFinishedGameWhereXWonViaRightColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"OOX", " X", " X"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOX", " OX", " O "}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via right column victory") - public void testFinishedGameWhereOWonViaRightColumnVictory() { + @DisplayName("Won games -> Finished game where O won via left column victory") + public void wonGamesFinishedGameWhereOWonViaLeftColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"OXX", "OX ", "O "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XXO", " XO", " O"}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via top row victory") - public void testFinishedGameWhereXWonViaTopRowVictory() { + @DisplayName("Won games -> Finished game where O won via middle column victory") + public void wonGamesFinishedGameWhereOWonViaMiddleColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", " OX", " O "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "O "}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via middle row victory") - public void testFinishedGameWhereXWonViaMiddleRowVictory() { + @DisplayName("Won games -> Finished game where O won via right column victory") + public void wonGamesFinishedGameWhereOWonViaRightColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XXO", " XO", " O"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"O ", "XXX", " O "}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via bottom row victory") - public void testFinishedGameWhereXWonViaBottomRowVictory() { + @DisplayName("Won games -> Finished game where X won via top row victory") + public void wonGamesFinishedGameWhereXWonViaTopRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "O "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{" OO", "O X", "XXX"}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via top row victory") - public void testFinishedGameWhereOWonViaTopRowVictory() { + @DisplayName("Won games -> Finished game where X won via middle row victory") + public void wonGamesFinishedGameWhereXWonViaMiddleRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"O ", "XXX", " O "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"OOO", "XXO", "XX "}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via middle row victory") - public void testFinishedGameWhereOWonViaMiddleRowVictory() { + @DisplayName("Won games -> Finished game where X won via bottom row victory") + public void wonGamesFinishedGameWhereXWonViaBottomRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{" OO", "O X", "XXX"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XX ", "OOO", "X "}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via bottom row victory") - public void testFinishedGameWhereOWonViaBottomRowVictory() { + @DisplayName("Won games -> Finished game where O won via top row victory") + public void wonGamesFinishedGameWhereOWonViaTopRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"OOO", "XXO", "XX "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOX", " XX", "OOO"}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via falling diagonal victory") - public void testFinishedGameWhereXWonViaFallingDiagonalVictory() { + @DisplayName("Won games -> Finished game where O won via middle row victory") + public void wonGamesFinishedGameWhereOWonViaMiddleRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XX ", "OOO", "X "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOO", " X ", " X"}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via rising diagonal victory") - public void testFinishedGameWhereXWonViaRisingDiagonalVictory() { + @DisplayName("Won games -> Finished game where O won via bottom row victory") + public void wonGamesFinishedGameWhereOWonViaBottomRowVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", " XX", "OOO"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"O X", "OX ", "X "}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via falling diagonal victory") - public void testFinishedGameWhereOWonViaFallingDiagonalVictory() { + @DisplayName("Won games -> Finished game where X won via falling diagonal victory") + public void wonGamesFinishedGameWhereXWonViaFallingDiagonalVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XOO", " X ", " X"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"OXX", "OOX", "X O"}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where O won via rising diagonal victory") - public void testFinishedGameWhereOWonViaRisingDiagonalVictory() { + @DisplayName("Won games -> Finished game where X won via rising diagonal victory") + public void wonGamesFinishedGameWhereXWonViaRisingDiagonalVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"O X", "OX ", "X "})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{" O", " OX", "OXX"}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via a row and a column victory") - public void testFinishedGameWhereXWonViaARowAndAColumnVictory() { + @DisplayName("Won games -> Finished game where O won via falling diagonal victory") + public void wonGamesFinishedGameWhereOWonViaFallingDiagonalVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"OXX", "OOX", "X O"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "XOO"}) - ).isEqualTo(GameState.WIN); } @Disabled("Remove to run test") @Test - @DisplayName("Finished game where X won via two diagonal victories") - public void testFinishedGameWhereXWonViaTwoDiagonalVictories() { + @DisplayName("Won games -> Finished game where O won via rising diagonal victory") + public void wonGamesFinishedGameWhereOWonViaRisingDiagonalVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{" O", " OX", "OXX"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOX", "OXO", "XOX"}) - ).isEqualTo(GameState.WIN); } - + @Disabled("Remove to run test") @Test - @DisplayName("Drawn games") - public void testDraw() { + @DisplayName("Won games -> Finished game where X won via a row and a column victory") + public void wonGamesFinishedGameWhereXWonViaARowAndAColumnVictory() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "XOO"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XOX", "XXO", "OXO"}) - ).isEqualTo(GameState.DRAW); } - + @Disabled("Remove to run test") @Test - @DisplayName("Another draw") - public void testAnotherDraw() { + @DisplayName("Won games -> Finished game where X won via two diagonal victories") + public void wonGamesFinishedGameWhereXWonViaTwoDiagonalVictories() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", "OXO", "XOX"})) + .isEqualTo(GameState.WIN); - assertThat( - stateOfTicTacToe.determineState(new String[]{"XXO", "OXX", "XOO"}) - ).isEqualTo(GameState.DRAW); } @Disabled("Remove to run test") @Test - @DisplayName("Ongoing game: one move in") - public void testOngoingGameOneMoveIn() { + @DisplayName("Drawn games -> Draw") + public void drawnGamesDraw() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", "XXO", "OXO"})) + .isEqualTo(GameState.DRAW); - assertThat( - stateOfTicTacToe.determineState(new String[]{" ", "X ", " "}) - ).isEqualTo(GameState.ONGOING); } - + @Disabled("Remove to run test") @Test - @DisplayName("Ongoing game: two moves in") - public void testOngoingGameTwoMovesIn() { + @DisplayName("Drawn games -> Another draw") + public void drawnGamesAnotherDraw() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"XXO", "OXX", "XOO"})) + .isEqualTo(GameState.DRAW); - assertThat( - stateOfTicTacToe.determineState(new String[]{"O ", " X ", " "}) - ).isEqualTo(GameState.ONGOING); } @Disabled("Remove to run test") @Test - @DisplayName("Ongoing game: five moves in") - public void testOngoingGameFiveMovesIn() { + @DisplayName("Ongoing games -> Ongoing game: one move in") + public void ongoingGamesOngoingGameOneMoveIn() { + + assertThat(stateOfTicTacToe.determineState(new String[]{" ", "X ", " "})) + .isEqualTo(GameState.ONGOING); - assertThat( - stateOfTicTacToe.determineState(new String[]{"X ", " XO", "OX "}) - ).isEqualTo(GameState.ONGOING); } @Disabled("Remove to run test") @Test - @DisplayName("Invalid board: X went twice") - public void testInvalidBoardXWentTwice() { + @DisplayName("Ongoing games -> Ongoing game: two moves in") + public void ongoingGamesOngoingGameTwoMovesIn() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"O ", " X ", " "})) + .isEqualTo(GameState.ONGOING); - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XX ", " ", " "})) - .withMessage("Wrong turn order: X went twice"); } - + @Disabled("Remove to run test") @Test - @DisplayName("Invalid board: O started") - public void testInvalidBoardOStarted() { + @DisplayName("Ongoing games -> Ongoing game: five moves in") + public void ongoingGamesOngoingGameFiveMovesIn() { + + assertThat(stateOfTicTacToe.determineState(new String[]{"X ", " XO", "OX "})) + .isEqualTo(GameState.ONGOING); - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"OOX", " ", " "})) - .withMessage("Wrong turn order: O started"); } @Disabled("Remove to run test") @Test - @DisplayName("Invalid board") - public void testInvalidBoard() { + @DisplayName("Invalid boards -> Invalid board: X went twice") + public void invalidBoardsInvalidBoardXWentTwice() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", " "})) - .withMessage("Impossible board: game should have ended after the game was won"); + .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XX ", " ", " "})) + .withMessage("Wrong turn order: X went twice"); + } @Disabled("Remove to run test") @Test - @DisplayName("Invalid board: players kept playing after a win") - public void testInvalidBoardPlayersKeptPlayingAfterAWin() { + @DisplayName("Invalid boards -> Invalid board: O started") + public void invalidBoardsInvalidBoardOStarted() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", "XOX"})) - .withMessage("Impossible board: game should have ended after the game was won"); + .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"OOX", " ", " "})) + .withMessage("Wrong turn order: O started"); + } @Disabled("Remove to run test") @Test - @DisplayName("Invalid board: O kept playing after X wins") - public void testInvalidBoardOKeptPlayingAfterXWins() { + @DisplayName("Invalid boards -> Invalid board: X won and O kept playing") + public void invalidBoardsInvalidBoardXWonAndOKeptPlaying() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"OO ", "XXX", " O "})) - .withMessage("Impossible board: game should have ended after the game was won"); + .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", " "})) + .withMessage("Impossible board: game should have ended after the game was won"); + } @Disabled("Remove to run test") @Test - @DisplayName("Invalid board: X kept playing after O wins") - public void testInvalidBoardXKeptPlayingAfterOWins() { + @DisplayName("Invalid boards -> Invalid board: players kept playing after a win") + public void invalidBoardsInvalidBoardPlayersKeptPlayingAfterAWin() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XX ", "OOO", " XX"})) - .withMessage("Impossible board: game should have ended after the game was won"); + .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", "XOX"})) + .withMessage("Impossible board: game should have ended after the game was won"); + } + } diff --git a/exercises/practice/sublist/src/test/java/RelationshipComputerTest.java b/exercises/practice/sublist/src/test/java/RelationshipComputerTest.java index bcb2d6f8d..73e4efbfb 100644 --- a/exercises/practice/sublist/src/test/java/RelationshipComputerTest.java +++ b/exercises/practice/sublist/src/test/java/RelationshipComputerTest.java @@ -4,208 +4,169 @@ import java.util.List; -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; public class RelationshipComputerTest { @Test @DisplayName("empty lists") - public void testThatTwoEmptyListsAreConsideredEqual() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - emptyList(), - emptyList()); - + public void emptyLists() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(), List.of()); assertThat(relationship).isEqualTo(Relationship.EQUAL); } @Disabled("Remove to run test") @Test @DisplayName("empty list within non empty list") - public void testEmptyListIsSublistOfNonEmptyList() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - emptyList(), - asList(1, 2, 3)); - + public void emptyListWithinNonEmptyList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(), List.of(1, 2, 3)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("non empty list contains empty list") - public void testNonEmptyListIsSuperlistOfEmptyList() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList('1', '2', '3'), - emptyList()); - + public void nonEmptyListContainsEmptyList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 3), List.of()); assertThat(relationship).isEqualTo(Relationship.SUPERLIST); } @Disabled("Remove to run test") @Test @DisplayName("list equals itself") - public void testListIsEqualToItself() { - List anyList = asList("1", "2", "3"); - - Relationship relationship = new RelationshipComputer().computeRelationship( - anyList, - anyList); - + public void listEqualsItself() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 3), List.of(1, 2, 3)); assertThat(relationship).isEqualTo(Relationship.EQUAL); } @Disabled("Remove to run test") @Test @DisplayName("different lists") - public void testDifferentListsOfTheSameLengthAreUnequal() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(1, 2, 3), - asList(2, 3, 4)); - + public void differentLists() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 3), List.of(2, 3, 4)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } @Disabled("Remove to run test") @Test @DisplayName("false start") - public void testSublistCheckDoesNotAbortAfterFalseStart() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList('1', '2', '5'), - asList('0', '1', '2', '3', '1', '2', '5', '6')); - + public void falseStart() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 5), List.of(0, 1, 2, 3, 1, 2, 5, 6)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("consecutive") - public void testSublistCheckHandlesExtraneousRepeatsOfFirstEntry() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList("1", "1", "2"), - asList("0", "1", "1", "1", "2", "1", "2")); - + public void consecutive() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 1, 2), List.of(0, 1, 1, 1, 2, 1, 2)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("sublist at start") - public void testSublistAtStart() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(0, 1, 2), - asList(0, 1, 2, 3, 4, 5)); - + public void sublistAtStart() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(0, 1, 2), List.of(0, 1, 2, 3, 4, 5)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("sublist in middle") - public void testSublistInMiddle() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList('2', '3', '4'), - asList('0', '1', '2', '3', '4', '5')); - + public void sublistInMiddle() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(2, 3, 4), List.of(0, 1, 2, 3, 4, 5)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("sublist at end") - public void testSublistAtEnd() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList("3", "4", "5"), - asList("0", "1", "2", "3", "4", "5")); - + public void sublistAtEnd() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(3, 4, 5), List.of(0, 1, 2, 3, 4, 5)); assertThat(relationship).isEqualTo(Relationship.SUBLIST); } @Disabled("Remove to run test") @Test @DisplayName("at start of superlist") - public void testAtStartOfSuperlist() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(0, 1, 2, 3, 4, 5), - asList(0, 1, 2)); - + public void atStartOfSuperlist() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(0, 1, 2, 3, 4, 5), List.of(0, 1, 2)); assertThat(relationship).isEqualTo(Relationship.SUPERLIST); } @Disabled("Remove to run test") @Test @DisplayName("in middle of superlist") - public void testInMiddleOfSuperlist() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList('0', '1', '2', '3', '4', '5'), - asList('2', '3')); - + public void inMiddleOfSuperlist() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(0, 1, 2, 3, 4, 5), List.of(2, 3)); assertThat(relationship).isEqualTo(Relationship.SUPERLIST); } @Disabled("Remove to run test") @Test @DisplayName("at end of superlist") - public void testAtEndOfSuperlist() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList("0", "1", "2", "3", "4", "5"), - asList("3", "4", "5")); - + public void atEndOfSuperlist() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(0, 1, 2, 3, 4, 5), List.of(3, 4, 5)); assertThat(relationship).isEqualTo(Relationship.SUPERLIST); } @Disabled("Remove to run test") @Test @DisplayName("first list missing element from second list") - public void testFirstListMissingElementFromSecondList() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(1, 3), - asList(1, 2, 3)); - + public void firstListMissingElementFromSecondList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 3), List.of(1, 2, 3)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } @Disabled("Remove to run test") @Test @DisplayName("second list missing element from first list") - public void testSecondListMissingElementFromFirstList() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList('1', '2', '3'), - asList('1', '3')); - + public void secondListMissingElementFromFirstList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 3), List.of(1, 3)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } @Disabled("Remove to run test") @Test @DisplayName("first list missing additional digits from second list") - public void testFirstListMissingAdditionalDigitsFromSecondList() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(1, 2), - asList(1, 22)); - + public void firstListMissingAdditionalDigitsFromSecondList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2), List.of(1, 22)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } @Disabled("Remove to run test") @Test @DisplayName("order matters to a list") - public void testThatListOrderingIsAccountedFor() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList("1", "2", "3"), - asList("3", "2", "1")); - + public void orderMattersToAList() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 2, 3), List.of(3, 2, 1)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } @Disabled("Remove to run test") @Test @DisplayName("same digits but different numbers") - public void testThatListsWithSameDigitsButDifferentNumbersAreUnequal() { - Relationship relationship = new RelationshipComputer<>().computeRelationship( - asList(1, 0, 1), - asList(10, 1)); - + public void sameDigitsButDifferentNumbers() { + Relationship relationship = new RelationshipComputer() + .computeRelationship(List.of(1, 0, 1), List.of(10, 1)); assertThat(relationship).isEqualTo(Relationship.UNEQUAL); } + } diff --git a/exercises/practice/sum-of-multiples/src/test/java/SumOfMultiplesTest.java b/exercises/practice/sum-of-multiples/src/test/java/SumOfMultiplesTest.java index b2736d8bd..0830c1a82 100644 --- a/exercises/practice/sum-of-multiples/src/test/java/SumOfMultiplesTest.java +++ b/exercises/practice/sum-of-multiples/src/test/java/SumOfMultiplesTest.java @@ -8,224 +8,129 @@ public class SumOfMultiplesTest { @Test @DisplayName("no multiples within limit") - public void testNoMultiplesWithinLimit() { - - int[] set = { - 3, - 5 - }; - int output = new SumOfMultiples(1, set).getSum(); - assertThat(output).isEqualTo(0); - + public void noMultiplesWithinLimit() { + assertThat(new SumOfMultiples(1, new int[]{3, 5}).getSum()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("one factor has multiples within limit") - public void testOneFactorHasMultiplesWithinLimit() { - - int[] set = { - 3, - 5 - }; - int output = new SumOfMultiples(4, set).getSum(); - assertThat(output).isEqualTo(3); - + public void oneFactorHasMultiplesWithinLimit() { + assertThat(new SumOfMultiples(4, new int[]{3, 5}).getSum()) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("more than one multiple within limit") - public void testMoreThanOneMultipleWithinLimit() { - - int[] set = { - 3 - }; - int output = new SumOfMultiples(7, set).getSum(); - assertThat(output).isEqualTo(9); - + public void moreThanOneMultipleWithinLimit() { + assertThat(new SumOfMultiples(7, new int[]{3}).getSum()) + .isEqualTo(9); } @Disabled("Remove to run test") @Test @DisplayName("more than one factor with multiples within limit") - public void testMoreThanOneFactorWithMultiplesWithinLimit() { - - int[] set = { - 3, - 5 - }; - int output = new SumOfMultiples(10, set).getSum(); - assertThat(output).isEqualTo(23); - + public void moreThanOneFactorWithMultiplesWithinLimit() { + assertThat(new SumOfMultiples(10, new int[]{3, 5}).getSum()) + .isEqualTo(23); } @Disabled("Remove to run test") @Test @DisplayName("each multiple is only counted once") - public void testEachMultipleIsOnlyCountedOnce() { - - int[] set = { - 3, - 5 - }; - int output = new SumOfMultiples(100, set).getSum(); - assertThat(output).isEqualTo(2318); - + public void eachMultipleIsOnlyCountedOnce() { + assertThat(new SumOfMultiples(100, new int[]{3, 5}).getSum()) + .isEqualTo(2318); } @Disabled("Remove to run test") @Test @DisplayName("a much larger limit") - public void testAMuchLargerLimit() { - - int[] set = { - 3, - 5 - }; - int output = new SumOfMultiples(1000, set).getSum(); - assertThat(output).isEqualTo(233168); - + public void aMuchLargerLimit() { + assertThat(new SumOfMultiples(1000, new int[]{3, 5}).getSum()) + .isEqualTo(233168); } @Disabled("Remove to run test") @Test @DisplayName("three factors") - public void testThreeFactors() { - - int[] set = { - 7, - 13, - 17 - }; - int output = new SumOfMultiples(20, set).getSum(); - assertThat(output).isEqualTo(51); - + public void threeFactors() { + assertThat(new SumOfMultiples(20, new int[]{7, 13, 17}).getSum()) + .isEqualTo(51); } @Disabled("Remove to run test") @Test @DisplayName("factors not relatively prime") - public void testFactorsNotRelativelyPrime() { - - int[] set = { - 4, - 6 - }; - int output = new SumOfMultiples(15, set).getSum(); - assertThat(output).isEqualTo(30); - + public void factorsNotRelativelyPrime() { + assertThat(new SumOfMultiples(15, new int[]{4, 6}).getSum()) + .isEqualTo(30); } @Disabled("Remove to run test") @Test @DisplayName("some pairs of factors relatively prime and some not") - public void testSomePairsOfFactorsRelativelyPrimeAndSomeNot() { - - int[] set = { - 5, - 6, - 8 - }; - int output = new SumOfMultiples(150, set).getSum(); - assertThat(output).isEqualTo(4419); - + public void somePairsOfFactorsRelativelyPrimeAndSomeNot() { + assertThat(new SumOfMultiples(150, new int[]{5, 6, 8}).getSum()) + .isEqualTo(4419); } @Disabled("Remove to run test") @Test @DisplayName("one factor is a multiple of another") - public void testOneFactorIsAMultipleOfAnother() { - - int[] set = { - 5, - 25 - }; - int output = new SumOfMultiples(51, set).getSum(); - assertThat(output).isEqualTo(275); - + public void oneFactorIsAMultipleOfAnother() { + assertThat(new SumOfMultiples(51, new int[]{5, 25}).getSum()) + .isEqualTo(275); } @Disabled("Remove to run test") @Test @DisplayName("much larger factors") - public void testMuchLargerFactors() { - - int[] set = { - 43, - 47 - }; - int output = new SumOfMultiples(10000, set).getSum(); - assertThat(output).isEqualTo(2203160); - + public void muchLargerFactors() { + assertThat(new SumOfMultiples(10000, new int[]{43, 47}).getSum()) + .isEqualTo(2203160); } @Disabled("Remove to run test") @Test @DisplayName("all numbers are multiples of 1") - public void testAllNumbersAreMultiplesOf1() { - - int[] set = { - 1 - }; - int output = new SumOfMultiples(100, set).getSum(); - assertThat(output).isEqualTo(4950); - + public void allNumbersAreMultiplesOf1() { + assertThat(new SumOfMultiples(100, new int[]{1}).getSum()) + .isEqualTo(4950); } @Disabled("Remove to run test") @Test @DisplayName("no factors means an empty sum") - public void testNoFactorsMeanAnEmptySum() { - - int[] set = {}; - int output = new SumOfMultiples(10000, set).getSum(); - assertThat(output).isEqualTo(0); - + public void noFactorsMeansAnEmptySum() { + assertThat(new SumOfMultiples(10000, new int[]{}).getSum()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("the only multiple of 0 is 0") - public void testSumOfMultiplesOfZeroIsZero() { - - int[] set = { - 0 - }; - int output = new SumOfMultiples(1, set).getSum(); - assertThat(output).isEqualTo(0); - + public void theOnlyMultipleOf0Is0() { + assertThat(new SumOfMultiples(1, new int[]{0}).getSum()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("the factor 0 does not affect the sum of multiples of other factors") - public void testFactorZeroDoesNotAffectTheSumOfMultiplesOfOtherFactors() { - - int[] set = { - 3, - 0 - }; - int output = new SumOfMultiples(4, set).getSum(); - assertThat(output).isEqualTo(3); - + public void theFactor0DoesNotAffectTheSumOfMultiplesOfOtherFactors() { + assertThat(new SumOfMultiples(4, new int[]{3, 0}).getSum()) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("solutions using include-exclude must extend to cardinality greater than 3") - public void testSolutionsUsingIncludeExcludeMustExtendToCardinalityGreater3() { - - int[] set = { - 2, - 3, - 5, - 7, - 11 - }; - int output = new SumOfMultiples(10000, set).getSum(); - assertThat(output).isEqualTo(39614537); - + public void solutionsUsingIncludeExcludeMustExtendToCardinalityGreaterThan3() { + assertThat(new SumOfMultiples(10000, new int[]{2, 3, 5, 7, 11}).getSum()) + .isEqualTo(39614537); } } diff --git a/exercises/practice/swift-scheduling/src/test/java/SwiftSchedulingTest.java b/exercises/practice/swift-scheduling/src/test/java/SwiftSchedulingTest.java index a73cb445a..9e0ea4b7a 100644 --- a/exercises/practice/swift-scheduling/src/test/java/SwiftSchedulingTest.java +++ b/exercises/practice/swift-scheduling/src/test/java/SwiftSchedulingTest.java @@ -6,212 +6,199 @@ import static org.assertj.core.api.Assertions.assertThat; -class SwiftSchedulingTest { +public class SwiftSchedulingTest { + @Test @DisplayName("NOW translates to two hours later") - void testNowAtNineAm() { + public void nowTranslatesToTwoHoursLater() { LocalDateTime meetingStart = LocalDateTime.parse("2012-02-13T09:00:00"); LocalDateTime expected = LocalDateTime.parse("2012-02-13T11:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "NOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "NOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("ASAP before one in the afternoon translates to today at five in the afternoon") - void testAsapBeforeOnePm() { + public void asapBeforeOneInTheAfternoonTranslatesToTodayAtFiveInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("1999-06-03T09:45:00"); LocalDateTime expected = LocalDateTime.parse("1999-06-03T17:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("ASAP at one in the afternoon translates to tomorrow at one in the afternoon") - void testAsapAtOnePm() { + public void asapAtOneInTheAfternoonTranslatesToTomorrowAtOneInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("2008-12-21T13:00:00"); LocalDateTime expected = LocalDateTime.parse("2008-12-22T13:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("ASAP after one in the afternoon translates to tomorrow at one in the afternoon") - void testAsapAfterOnePm() { + public void asapAfterOneInTheAfternoonTranslatesToTomorrowAtOneInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("2008-12-21T14:50:00"); LocalDateTime expected = LocalDateTime.parse("2008-12-22T13:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "ASAP")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW on Monday translates to Friday at five in the afternoon") - void testEowOnMonday() { + public void eowOnMondayTranslatesToFridayAtFiveInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("2025-02-03T16:00:00"); LocalDateTime expected = LocalDateTime.parse("2025-02-07T17:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW on Tuesday translates to Friday at five in the afternoon") - void testEowOnTuesday() { + public void eowOnTuesdayTranslatesToFridayAtFiveInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("1997-04-29T10:50:00"); LocalDateTime expected = LocalDateTime.parse("1997-05-02T17:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW on Wednesday translates to Friday at five in the afternoon") - void testEowOnWednesday() { + public void eowOnWednesdayTranslatesToFridayAtFiveInTheAfternoon() { LocalDateTime meetingStart = LocalDateTime.parse("2005-09-14T11:00:00"); LocalDateTime expected = LocalDateTime.parse("2005-09-16T17:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW on Thursday translates to Sunday at eight in the evening") - void testEowOnThursday() { + public void eowOnThursdayTranslatesToSundayAtEightInTheEvening() { LocalDateTime meetingStart = LocalDateTime.parse("2011-05-19T08:30:00"); LocalDateTime expected = LocalDateTime.parse("2011-05-22T20:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW on Friday translates to Sunday at eight in the evening") - void testEowOnFriday() { + public void eowOnFridayTranslatesToSundayAtEightInTheEvening() { LocalDateTime meetingStart = LocalDateTime.parse("2022-08-05T14:00:00"); LocalDateTime expected = LocalDateTime.parse("2022-08-07T20:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("EOW translates to leap day") - void testEowDuringLeapYear() { + public void eowTranslatesToLeapDay() { LocalDateTime meetingStart = LocalDateTime.parse("2008-02-25T10:30:00"); LocalDateTime expected = LocalDateTime.parse("2008-02-29T17:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "EOW")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName( - "2M before the second month of this year translates to the first workday of the second month of this year" - ) - void test2MInJanuary() { + @DisplayName("2M before the second month of this year translates to the first " + + "workday of the second month of this year") + public void test2mBeforeTheSecondMonthOfThisYearTranslatesToTheFirstWorkdayOf() { LocalDateTime meetingStart = LocalDateTime.parse("2007-01-02T14:15:00"); LocalDateTime expected = LocalDateTime.parse("2007-02-01T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "2M"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "2M")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("11M in the eleventh month translates to the first workday of the eleventh month of next year") - void test11MInNovember() { + @DisplayName("11M in the eleventh month translates to the first workday of the " + + "eleventh month of next year") + public void test11mInTheEleventhMonthTranslatesToTheFirstWorkdayOfTheEleventh() { LocalDateTime meetingStart = LocalDateTime.parse("2013-11-21T15:30:00"); LocalDateTime expected = LocalDateTime.parse("2014-11-03T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "11M"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "11M")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("4M in the ninth month translates to the first workday of the fourth month of next year") - void test4MInNovember() { + @DisplayName("4M in the eleventh month translates to the first workday of the fourth " + + "month of next year") + public void test4mInTheEleventhMonthTranslatesToTheFirstWorkdayOfTheFourthMon() { LocalDateTime meetingStart = LocalDateTime.parse("2019-11-18T15:15:00"); LocalDateTime expected = LocalDateTime.parse("2020-04-01T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "4M"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "4M")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Q1 in the first quarter translates to the last workday of the first quarter of this year") - void testQ1InQ1() { + @DisplayName("Q1 in the first quarter translates to the last workday of the first " + + "quarter of this year") + public void q1InTheFirstQuarterTranslatesToTheLastWorkdayOfTheFirstQuarterOfT() { LocalDateTime meetingStart = LocalDateTime.parse("2003-01-01T10:45:00"); LocalDateTime expected = LocalDateTime.parse("2003-03-31T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "Q1"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "Q1")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Q4 in the second quarter translates to the last workday of the fourth quarter of this year") - void testQ4InQ2() { + @DisplayName("Q4 in the second quarter translates to the last workday of the fourth " + + "quarter of this year") + public void q4InTheSecondQuarterTranslatesToTheLastWorkdayOfTheFourthQuarterO() { LocalDateTime meetingStart = LocalDateTime.parse("2001-04-09T09:00:00"); LocalDateTime expected = LocalDateTime.parse("2001-12-31T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "Q4"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "Q4")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("Q3 in the fourth quarter translates to the last workday of the third quarter of next year") - void testQ3InQ4() { + @DisplayName("Q3 in the fourth quarter translates to the last workday of the third " + + "quarter of next year") + public void q3InTheFourthQuarterTranslatesToTheLastWorkdayOfTheThirdQuarterOf() { LocalDateTime meetingStart = LocalDateTime.parse("2022-10-06T11:00:00"); LocalDateTime expected = LocalDateTime.parse("2023-09-29T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "Q3"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "Q3")) + .isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName( - "Q2 starting in the last month of the second quarter " + - "translates to the last workday of the second quarter of this year" - ) - void testQ2InQ2() { + @DisplayName("Q2 starting in the last month of the second quarter translates to the " + + "last workday of the second quarter of this year") + public void q2StartingInTheLastMonthOfTheSecondQuarterTranslatesToTheLastWork() { LocalDateTime meetingStart = LocalDateTime.parse("2019-06-15T09:50:00"); LocalDateTime expected = LocalDateTime.parse("2019-06-28T08:00:00"); - LocalDateTime actual = SwiftScheduling.convertToDeliveryDate(meetingStart, "Q2"); - - assertThat(actual).isEqualTo(expected); + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "Q2")) + .isEqualTo(expected); } + } diff --git a/exercises/practice/tournament/src/test/java/TournamentTest.java b/exercises/practice/tournament/src/test/java/TournamentTest.java index 94accd8fb..e73db8545 100644 --- a/exercises/practice/tournament/src/test/java/TournamentTest.java +++ b/exercises/practice/tournament/src/test/java/TournamentTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,184 +6,196 @@ public class TournamentTest { - private Tournament tournament; - - @BeforeEach - public void setUp() { - tournament = new Tournament(); - } - @Test @DisplayName("just the header if no input") public void justTheHeaderIfNoInput() { - assertThat(tournament.printTable()) - .isEqualTo("Team | MP | W | D | L | P\n"); + Tournament tournament = new Tournament(); + assertThat(tournament.printTable()).isEqualTo("Team | MP | W | D | L | P\n"); } @Disabled("Remove to run test") @Test @DisplayName("a win is three points, a loss is zero points") public void aWinIsThreePointsALossIsZeroPoints() { + Tournament tournament = new Tournament(); tournament.applyResults("Allegoric Alaskans;Blithering Badgers;win"); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" + - "Blithering Badgers | 1 | 0 | 0 | 1 | 0\n"); + "Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" + + "Blithering Badgers | 1 | 0 | 0 | 1 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("a win can also be expressed as a loss") public void aWinCanAlsoBeExpressedAsALoss() { + Tournament tournament = new Tournament(); tournament.applyResults("Blithering Badgers;Allegoric Alaskans;loss"); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" + - "Blithering Badgers | 1 | 0 | 0 | 1 | 0\n"); + "Allegoric Alaskans | 1 | 1 | 0 | 0 | 3\n" + + "Blithering Badgers | 1 | 0 | 0 | 1 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("a different team can win") public void aDifferentTeamCanWin() { + Tournament tournament = new Tournament(); tournament.applyResults("Blithering Badgers;Allegoric Alaskans;win"); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Blithering Badgers | 1 | 1 | 0 | 0 | 3\n" + - "Allegoric Alaskans | 1 | 0 | 0 | 1 | 0\n"); + "Blithering Badgers | 1 | 1 | 0 | 0 | 3\n" + + "Allegoric Alaskans | 1 | 0 | 0 | 1 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("a draw is one point each") public void aDrawIsOnePointEach() { + Tournament tournament = new Tournament(); tournament.applyResults("Allegoric Alaskans;Blithering Badgers;draw"); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 1 | 0 | 1 | 0 | 1\n" + - "Blithering Badgers | 1 | 0 | 1 | 0 | 1\n"); + "Allegoric Alaskans | 1 | 0 | 1 | 0 | 1\n" + + "Blithering Badgers | 1 | 0 | 1 | 0 | 1\n"); } @Disabled("Remove to run test") @Test @DisplayName("There can be more than one match") public void thereCanBeMoreThanOneMatch() { + Tournament tournament = new Tournament(); tournament.applyResults( "Allegoric Alaskans;Blithering Badgers;win\n" + - "Allegoric Alaskans;Blithering Badgers;win"); + "Allegoric Alaskans;Blithering Badgers;win\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" + - "Blithering Badgers | 2 | 0 | 0 | 2 | 0\n"); + "Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" + + "Blithering Badgers | 2 | 0 | 0 | 2 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("There can be more than one winner") public void thereCanBeMoreThanOneWinner() { + Tournament tournament = new Tournament(); tournament.applyResults( "Allegoric Alaskans;Blithering Badgers;loss\n" + - "Allegoric Alaskans;Blithering Badgers;win"); + "Allegoric Alaskans;Blithering Badgers;win\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 2 | 1 | 0 | 1 | 3\n" + - "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n"); + "Allegoric Alaskans | 2 | 1 | 0 | 1 | 3\n" + + "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n"); } @Disabled("Remove to run test") @Test @DisplayName("There can be more than two teams") public void thereCanBeMoreThanTwoTeams() { + Tournament tournament = new Tournament(); tournament.applyResults( "Allegoric Alaskans;Blithering Badgers;win\n" + - "Blithering Badgers;Courageous Californians;win\n" + - "Courageous Californians;Allegoric Alaskans;loss"); + "Blithering Badgers;Courageous Californians;win\n" + + "Courageous Californians;Allegoric Alaskans;loss\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" + - "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n" + - "Courageous Californians | 2 | 0 | 0 | 2 | 0\n"); + "Allegoric Alaskans | 2 | 2 | 0 | 0 | 6\n" + + "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n" + + "Courageous Californians | 2 | 0 | 0 | 2 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("typical input") public void typicalInput() { + Tournament tournament = new Tournament(); tournament.applyResults( "Allegoric Alaskans;Blithering Badgers;win\n" + - "Devastating Donkeys;Courageous Californians;draw\n" + - "Devastating Donkeys;Allegoric Alaskans;win\n" + - "Courageous Californians;Blithering Badgers;loss\n" + - "Blithering Badgers;Devastating Donkeys;loss\n" + - "Allegoric Alaskans;Courageous Californians;win"); + "Devastating Donkeys;Courageous Californians;draw\n" + + "Devastating Donkeys;Allegoric Alaskans;win\n" + + "Courageous Californians;Blithering Badgers;loss\n" + + "Blithering Badgers;Devastating Donkeys;loss\n" + + "Allegoric Alaskans;Courageous Californians;win\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + - "Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" + - "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + - "Courageous Californians | 3 | 0 | 1 | 2 | 1\n"); + "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + + "Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" + + "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + + "Courageous Californians | 3 | 0 | 1 | 2 | 1\n"); } @Disabled("Remove to run test") @Test @DisplayName("incomplete competition (not all pairs have played)") - public void incompleteCompetition() { + public void incompleteCompetitionNotAllPairsHavePlayed() { + Tournament tournament = new Tournament(); tournament.applyResults( "Allegoric Alaskans;Blithering Badgers;loss\n" + - "Devastating Donkeys;Allegoric Alaskans;loss\n" + - "Courageous Californians;Blithering Badgers;draw\n" + - "Allegoric Alaskans;Courageous Californians;win"); + "Devastating Donkeys;Allegoric Alaskans;loss\n" + + "Courageous Californians;Blithering Badgers;draw\n" + + "Allegoric Alaskans;Courageous Californians;win\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" + - "Blithering Badgers | 2 | 1 | 1 | 0 | 4\n" + - "Courageous Californians | 2 | 0 | 1 | 1 | 1\n" + - "Devastating Donkeys | 1 | 0 | 0 | 1 | 0\n"); + "Allegoric Alaskans | 3 | 2 | 0 | 1 | 6\n" + + "Blithering Badgers | 2 | 1 | 1 | 0 | 4\n" + + "Courageous Californians | 2 | 0 | 1 | 1 | 1\n" + + "Devastating Donkeys | 1 | 0 | 0 | 1 | 0\n"); } @Disabled("Remove to run test") @Test @DisplayName("ties broken alphabetically") public void tiesBrokenAlphabetically() { + Tournament tournament = new Tournament(); tournament.applyResults( "Courageous Californians;Devastating Donkeys;win\n" + - "Allegoric Alaskans;Blithering Badgers;win\n" + - "Devastating Donkeys;Allegoric Alaskans;loss\n" + - "Courageous Californians;Blithering Badgers;win\n" + - "Blithering Badgers;Devastating Donkeys;draw\n" + - "Allegoric Alaskans;Courageous Californians;draw"); + "Allegoric Alaskans;Blithering Badgers;win\n" + + "Devastating Donkeys;Allegoric Alaskans;loss\n" + + "Courageous Californians;Blithering Badgers;win\n" + + "Blithering Badgers;Devastating Donkeys;draw\n" + + "Allegoric Alaskans;Courageous Californians;draw\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Allegoric Alaskans | 3 | 2 | 1 | 0 | 7\n" + - "Courageous Californians | 3 | 2 | 1 | 0 | 7\n" + - "Blithering Badgers | 3 | 0 | 1 | 2 | 1\n" + - "Devastating Donkeys | 3 | 0 | 1 | 2 | 1\n"); + "Allegoric Alaskans | 3 | 2 | 1 | 0 | 7\n" + + "Courageous Californians | 3 | 2 | 1 | 0 | 7\n" + + "Blithering Badgers | 3 | 0 | 1 | 2 | 1\n" + + "Devastating Donkeys | 3 | 0 | 1 | 2 | 1\n"); } @Disabled("Remove to run test") @Test @DisplayName("ensure points sorted numerically") - public void pointsSortedNumerically() { + public void ensurePointsSortedNumerically() { + Tournament tournament = new Tournament(); tournament.applyResults( "Devastating Donkeys;Blithering Badgers;win\n" + - "Devastating Donkeys;Blithering Badgers;win\n" + - "Devastating Donkeys;Blithering Badgers;win\n" + - "Devastating Donkeys;Blithering Badgers;win\n" + - "Blithering Badgers;Devastating Donkeys;win"); + "Devastating Donkeys;Blithering Badgers;win\n" + + "Devastating Donkeys;Blithering Badgers;win\n" + + "Devastating Donkeys;Blithering Badgers;win\n" + + "Blithering Badgers;Devastating Donkeys;win\n" + ); assertThat(tournament.printTable()) .isEqualTo( "Team | MP | W | D | L | P\n" + - "Devastating Donkeys | 5 | 4 | 0 | 1 | 12\n" + - "Blithering Badgers | 5 | 1 | 0 | 4 | 3\n"); + "Devastating Donkeys | 5 | 4 | 0 | 1 | 12\n" + + "Blithering Badgers | 5 | 1 | 0 | 4 | 3\n"); } + } diff --git a/exercises/practice/transpose/src/test/java/TransposeTest.java b/exercises/practice/transpose/src/test/java/TransposeTest.java index 8a4b18686..1a0ee509b 100644 --- a/exercises/practice/transpose/src/test/java/TransposeTest.java +++ b/exercises/practice/transpose/src/test/java/TransposeTest.java @@ -1,54 +1,50 @@ -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; -public class TransposeTest { - private Transpose transpose; +import static org.assertj.core.api.Assertions.assertThat; - @BeforeEach - public void setup() { - transpose = new Transpose(); - } +public class TransposeTest { @Test @DisplayName("empty string") public void emptyString() { - assertThat(transpose.transpose("")).isEqualTo(""); + Transpose transpose = new Transpose(); + assertThat(transpose.transpose("")) + .isEqualTo(""); } @Disabled("Remove to run test") @Test @DisplayName("two characters in a row") public void twoCharactersInARow() { + Transpose transpose = new Transpose(); assertThat(transpose.transpose("A1")) - .isEqualTo( - "A" + - "\n1"); + .isEqualTo( + "A\n" + + "1"); } @Disabled("Remove to run test") @Test @DisplayName("two characters in a column") public void twoCharactersInAColumn() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "A\n" + "1")) - .isEqualTo("A1"); + .isEqualTo("A1"); } @Disabled("Remove to run test") @Test @DisplayName("simple") public void simple() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "ABC\n" + "123")) - .isEqualTo( + .isEqualTo( "A1\n" + "B2\n" + "C3"); @@ -58,8 +54,9 @@ public void simple() { @Test @DisplayName("single line") public void singleLine() { + Transpose transpose = new Transpose(); assertThat(transpose.transpose("Single line.")) - .isEqualTo( + .isEqualTo( "S\n" + "i\n" + "n\n" + @@ -78,11 +75,11 @@ public void singleLine() { @Test @DisplayName("first line longer than second line") public void firstLineLongerThanSecondLine() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "The fourth line.\n" + "The fifth line.")) - .isEqualTo( + .isEqualTo( "TT\n" + "hh\n" + "ee\n" + @@ -105,11 +102,11 @@ public void firstLineLongerThanSecondLine() { @Test @DisplayName("second line longer than first line") public void secondLineLongerThanFirstLine() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "The first line.\n" + "The second line.")) - .isEqualTo( + .isEqualTo( "TT\n" + "hh\n" + "ee\n" + @@ -132,13 +129,13 @@ public void secondLineLongerThanFirstLine() { @Test @DisplayName("mixed line length") public void mixedLineLength() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "The longest line.\n" + "A long line.\n" + "A longer line.\n" + "A line.")) - .isEqualTo( + .isEqualTo( "TAAA\n" + "h \n" + "elll\n" + @@ -162,14 +159,14 @@ public void mixedLineLength() { @Test @DisplayName("square") public void square() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "HEART\n" + "EMBER\n" + "ABUSE\n" + "RESIN\n" + "TREND")) - .isEqualTo( + .isEqualTo( "HEART\n" + "EMBER\n" + "ABUSE\n" + @@ -181,13 +178,13 @@ public void square() { @Test @DisplayName("rectangle") public void rectangle() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "FRACTURE\n" + "OUTLINED\n" + "BLOOMING\n" + "SEPTETTE")) - .isEqualTo( + .isEqualTo( "FOBS\n" + "RULE\n" + "ATOP\n" + @@ -202,15 +199,15 @@ public void rectangle() { @Test @DisplayName("triangle") public void triangle() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "T\n" + "EE\n" + "AAA\n" + "SSSS\n" + "EEEEE\n" + "RRRRRR")) - .isEqualTo( + .isEqualTo( "TEASER\n" + " EASER\n" + " ASER\n" + @@ -218,20 +215,20 @@ public void triangle() { " ER\n" + " R"); } - + @Disabled("Remove to run test") @Test @DisplayName("jagged triangle") public void jaggedTriangle() { - assertThat( - transpose.transpose( + Transpose transpose = new Transpose(); + assertThat(transpose.transpose( "11\n" + "2\n" + "3333\n" + "444\n" + "555555\n" + "66666")) - .isEqualTo( + .isEqualTo( "123456\n" + "1 3456\n" + " 3456\n" + @@ -239,4 +236,5 @@ public void jaggedTriangle() { " 56\n" + " 5"); } + } diff --git a/exercises/practice/tree-building/src/test/java/BuildTreeTest.java b/exercises/practice/tree-building/src/test/java/BuildTreeTest.java index e11bc2990..38184d428 100644 --- a/exercises/practice/tree-building/src/test/java/BuildTreeTest.java +++ b/exercises/practice/tree-building/src/test/java/BuildTreeTest.java @@ -1,210 +1,214 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.ArrayList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + public class BuildTreeTest { @Test - @DisplayName("Empty list") - public void testEmptyList() throws InvalidRecordsException { + @DisplayName("empty list") + public void emptyList() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); - TreeNode root = new BuildTree().buildTree(records); assertThat(root).isNull(); } @Disabled("Remove to run test") @Test - @DisplayName("Single record") - public void testOneRecord() throws InvalidRecordsException { + @DisplayName("single record") + public void singleRecord() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); - Record record = new Record(0, 0); - records.add(record); - + records.add(new Record(0, 0)); TreeNode root = new BuildTree().buildTree(records); - assertThat(root.getNodeId()).isEqualTo(0); - assertNodeIsLeaf(root); + assertThat(root).isNotNull(); + assertNode(root, 0); } @Disabled("Remove to run test") @Test - @DisplayName("Three records in order") - public void testThreeRecordsInOrder() throws InvalidRecordsException { + @DisplayName("three records in order") + public void threeRecordsInOrder() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(0, 0)); records.add(new Record(1, 0)); records.add(new Record(2, 0)); - TreeNode root = new BuildTree().buildTree(records); - assertNodeIsBranchWithNNumberOfChildren(root, 2); - assertNodeIsLeaf(root.getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(1)); - - assertThat(root.getNodeId()).isEqualTo(0); - assertThat(root.getChildren().get(0).getNodeId()).isEqualTo(1); - assertThat(root.getChildren().get(1).getNodeId()).isEqualTo(2); + assertThat(root).isNotNull(); + assertNode(root, 0, 1, 2); + assertNode(root.getChildren().get(0), 1); + assertNode(root.getChildren().get(1), 2); } @Disabled("Remove to run test") @Test - @DisplayName("Three records in reverse order") - public void testThreeRecordsInReverseOrder() throws InvalidRecordsException { + @DisplayName("three records in reverse order") + public void threeRecordsInReverseOrder() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(2, 0)); records.add(new Record(1, 0)); records.add(new Record(0, 0)); - TreeNode root = new BuildTree().buildTree(records); - assertNodeIsBranchWithNNumberOfChildren(root, 2); - assertNodeIsLeaf(root.getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(1)); - - assertThat(root.getNodeId()).isEqualTo(0); - assertThat(root.getChildren().get(0).getNodeId()).isEqualTo(1); - assertThat(root.getChildren().get(1).getNodeId()).isEqualTo(2); + assertThat(root).isNotNull(); + assertNode(root, 0, 1, 2); + assertNode(root.getChildren().get(0), 1); + assertNode(root.getChildren().get(1), 2); } @Disabled("Remove to run test") @Test - @DisplayName("More than two children") - public void testRecordsWithMoreThanTwoChildren() throws InvalidRecordsException { + @DisplayName("more than two children") + public void moreThanTwoChildren() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(0, 0)); records.add(new Record(1, 0)); records.add(new Record(2, 0)); records.add(new Record(3, 0)); - TreeNode root = new BuildTree().buildTree(records); - assertNodeIsBranchWithNNumberOfChildren(root, 3); - assertNodeIsLeaf(root.getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(1)); - assertNodeIsLeaf(root.getChildren().get(2)); - - assertThat(root.getNodeId()).isEqualTo(0); - assertThat(root.getChildren().get(0).getNodeId()).isEqualTo(1); - assertThat(root.getChildren().get(1).getNodeId()).isEqualTo(2); - assertThat(root.getChildren().get(2).getNodeId()).isEqualTo(3); + assertThat(root).isNotNull(); + assertNode(root, 0, 1, 2, 3); + assertNode(root.getChildren().get(0), 1); + assertNode(root.getChildren().get(1), 2); + assertNode(root.getChildren().get(2), 3); } @Disabled("Remove to run test") @Test - @DisplayName("Binary tree") - public void testBinaryTree() throws InvalidRecordsException { + @DisplayName("binary tree") + public void binaryTree() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); - records.add(new Record(6, 2)); - records.add(new Record(0, 0)); - records.add(new Record(3, 1)); + records.add(new Record(5, 1)); + records.add(new Record(3, 2)); records.add(new Record(2, 0)); records.add(new Record(4, 1)); - records.add(new Record(5, 2)); records.add(new Record(1, 0)); - + records.add(new Record(0, 0)); + records.add(new Record(6, 2)); TreeNode root = new BuildTree().buildTree(records); - - assertNodeIsBranchWithNNumberOfChildren(root, 2); - assertNodeIsBranchWithNNumberOfChildren(root.getChildren().get(0), 2); - assertNodeIsBranchWithNNumberOfChildren(root.getChildren().get(1), 2); - assertNodeIsLeaf(root.getChildren().get(0).getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(0).getChildren().get(1)); - assertNodeIsLeaf(root.getChildren().get(1).getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(1).getChildren().get(1)); - - assertThat(root.getNodeId()).isEqualTo(0); - assertThat(root.getChildren().get(0).getNodeId()).isEqualTo(1); - assertThat(root.getChildren().get(1).getNodeId()).isEqualTo(2); - assertThat(root.getChildren().get(0).getChildren().get(0).getNodeId()).isEqualTo(3); - assertThat(root.getChildren().get(0).getChildren().get(1).getNodeId()).isEqualTo(4); - assertThat(root.getChildren().get(1).getChildren().get(0).getNodeId()).isEqualTo(5); - assertThat(root.getChildren().get(1).getChildren().get(1).getNodeId()).isEqualTo(6); + assertThat(root).isNotNull(); + assertNode(root, 0, 1, 2); + assertNode(root.getChildren().get(0), 1, 4, 5); + assertNode(root.getChildren().get(0).getChildren().get(0), 4); + assertNode(root.getChildren().get(0).getChildren().get(1), 5); + assertNode(root.getChildren().get(1), 2, 3, 6); + assertNode(root.getChildren().get(1).getChildren().get(0), 3); + assertNode(root.getChildren().get(1).getChildren().get(1), 6); } @Disabled("Remove to run test") @Test - @DisplayName("Unbalanced tree") - public void testUnbalancedTree() throws InvalidRecordsException { + @DisplayName("unbalanced tree") + public void unbalancedTree() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); - records.add(new Record(0, 0)); - records.add(new Record(1, 0)); + records.add(new Record(5, 2)); + records.add(new Record(3, 2)); records.add(new Record(2, 0)); - records.add(new Record(3, 1)); records.add(new Record(4, 1)); - records.add(new Record(5, 1)); + records.add(new Record(1, 0)); + records.add(new Record(0, 0)); records.add(new Record(6, 2)); - TreeNode root = new BuildTree().buildTree(records); - assertNodeIsBranchWithNNumberOfChildren(root, 2); - assertNodeIsBranchWithNNumberOfChildren(root.getChildren().get(0), 3); - assertNodeIsBranchWithNNumberOfChildren(root.getChildren().get(1), 1); - assertNodeIsLeaf(root.getChildren().get(0).getChildren().get(0)); - assertNodeIsLeaf(root.getChildren().get(0).getChildren().get(1)); - assertNodeIsLeaf(root.getChildren().get(0).getChildren().get(2)); - assertNodeIsLeaf(root.getChildren().get(1).getChildren().get(0)); - - assertThat(root.getNodeId()).isEqualTo(0); - assertThat(root.getChildren().get(0).getNodeId()).isEqualTo(1); - assertThat(root.getChildren().get(1).getNodeId()).isEqualTo(2); - assertThat(root.getChildren().get(0).getChildren().get(0).getNodeId()).isEqualTo(3); - assertThat(root.getChildren().get(0).getChildren().get(1).getNodeId()).isEqualTo(4); - assertThat(root.getChildren().get(0).getChildren().get(2).getNodeId()).isEqualTo(5); - assertThat(root.getChildren().get(1).getChildren().get(0).getNodeId()).isEqualTo(6); + assertThat(root).isNotNull(); + assertNode(root, 0, 1, 2); + assertNode(root.getChildren().get(0), 1, 4); + assertNode(root.getChildren().get(0).getChildren().get(0), 4); + assertNode(root.getChildren().get(1), 2, 3, 5, 6); + assertNode(root.getChildren().get(1).getChildren().get(0), 3); + assertNode(root.getChildren().get(1).getChildren().get(1), 5); + assertNode(root.getChildren().get(1).getChildren().get(2), 6); } @Disabled("Remove to run test") @Test - @DisplayName("Root has parent") - public void testRootNodeHasParent() { + @DisplayName("one root node and has parent") + public void oneRootNodeAndHasParent() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(0, 1)); - records.add(new Record(1, 0)); - - BuildTree test = new BuildTree(); + assertThatExceptionOfType(InvalidRecordsException.class) + .isThrownBy(() -> new BuildTree().buildTree(records)); + } + @Disabled("Remove to run test") + @Test + @DisplayName("root node has parent") + public void rootNodeHasParent() throws InvalidRecordsException { + ArrayList records = new ArrayList<>(); + records.add(new Record(0, 1)); + records.add(new Record(1, 0)); assertThatExceptionOfType(InvalidRecordsException.class) - .isThrownBy(() -> test.buildTree(records)) - .withMessage("Invalid Records"); + .isThrownBy(() -> new BuildTree().buildTree(records)); } @Disabled("Remove to run test") @Test - @DisplayName("No root node") - public void testNoRootNode() { + @DisplayName("no root node") + public void noRootNode() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(1, 0)); records.add(new Record(2, 0)); + assertThatExceptionOfType(InvalidRecordsException.class) + .isThrownBy(() -> new BuildTree().buildTree(records)); + } - BuildTree test = new BuildTree(); + @Disabled("Remove to run test") + @Test + @DisplayName("duplicate node") + public void duplicateNode() throws InvalidRecordsException { + ArrayList records = new ArrayList<>(); + records.add(new Record(0, 0)); + records.add(new Record(1, 0)); + records.add(new Record(1, 0)); + assertThatExceptionOfType(InvalidRecordsException.class) + .isThrownBy(() -> new BuildTree().buildTree(records)); + } + @Disabled("Remove to run test") + @Test + @DisplayName("duplicate root") + public void duplicateRoot() throws InvalidRecordsException { + ArrayList records = new ArrayList<>(); + records.add(new Record(0, 0)); + records.add(new Record(0, 0)); assertThatExceptionOfType(InvalidRecordsException.class) - .isThrownBy(() -> test.buildTree(records)) - .withMessage("Invalid Records"); + .isThrownBy(() -> new BuildTree().buildTree(records)); } @Disabled("Remove to run test") @Test - @DisplayName("Non continuous records") - public void testNonContinuousRecords() { + @DisplayName("non-continuous") + public void nonContinuous() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(2, 0)); records.add(new Record(4, 2)); records.add(new Record(1, 0)); records.add(new Record(0, 0)); + assertThatExceptionOfType(InvalidRecordsException.class) + .isThrownBy(() -> new BuildTree().buildTree(records)); + } - BuildTree test = new BuildTree(); - + @Disabled("Remove to run test") + @Test + @DisplayName("cycle directly") + public void cycleDirectly() throws InvalidRecordsException { + ArrayList records = new ArrayList<>(); + records.add(new Record(5, 2)); + records.add(new Record(3, 2)); + records.add(new Record(2, 2)); + records.add(new Record(4, 1)); + records.add(new Record(1, 0)); + records.add(new Record(0, 0)); + records.add(new Record(6, 3)); assertThatExceptionOfType(InvalidRecordsException.class) - .isThrownBy(() -> test.buildTree(records)) - .withMessage("Invalid Records"); + .isThrownBy(() -> new BuildTree().buildTree(records)); } @Disabled("Remove to run test") @Test - @DisplayName("Cycle indirectly") - public void testCycleIndirectly() { + @DisplayName("cycle indirectly") + public void cycleIndirectly() throws InvalidRecordsException { ArrayList records = new ArrayList<>(); records.add(new Record(5, 2)); records.add(new Record(3, 2)); @@ -213,19 +217,27 @@ public void testCycleIndirectly() { records.add(new Record(1, 0)); records.add(new Record(0, 0)); records.add(new Record(6, 3)); - - BuildTree test = new BuildTree(); - assertThatExceptionOfType(InvalidRecordsException.class) - .isThrownBy(() -> test.buildTree(records)) - .withMessage("Invalid Records"); + .isThrownBy(() -> new BuildTree().buildTree(records)); } - private void assertNodeIsLeaf(TreeNode node) { - assertThat(node.getChildren().size()).isEqualTo(0); + @Disabled("Remove to run test") + @Test + @DisplayName("higher id parent of lower id") + public void higherIdParentOfLowerId() throws InvalidRecordsException { + ArrayList records = new ArrayList<>(); + records.add(new Record(0, 0)); + records.add(new Record(2, 0)); + records.add(new Record(1, 2)); + assertThatExceptionOfType(InvalidRecordsException.class) + .isThrownBy(() -> new BuildTree().buildTree(records)); } - private void assertNodeIsBranchWithNNumberOfChildren(TreeNode node, int childrenCount) { - assertThat(node.getChildren().size()).isEqualTo(childrenCount); + private void assertNode(TreeNode actual, int expectedId, int... expectedChildren) { + assertThat(actual.getNodeId()).isEqualTo(expectedId); + assertThat(actual.getChildren()).hasSize(expectedChildren.length); + for (int i = 0; i < expectedChildren.length; i++) { + assertThat(actual.getChildren().get(i).getNodeId()).isEqualTo(expectedChildren[i]); + } } } diff --git a/exercises/practice/triangle/src/test/java/TriangleTest.java b/exercises/practice/triangle/src/test/java/TriangleTest.java index e7dc8f630..d5d07163d 100644 --- a/exercises/practice/triangle/src/test/java/TriangleTest.java +++ b/exercises/practice/triangle/src/test/java/TriangleTest.java @@ -1,187 +1,177 @@ -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class TriangleTest { @Test - @DisplayName("equilateral triangle") - public void equilateralTrianglesHaveEqualSides() throws TriangleException { - Triangle triangle = new Triangle(2, 2, 2); - - assertThat(triangle.isEquilateral()).isTrue(); + @DisplayName("equilateral triangle -> all sides are equal") + public void equilateralTriangleAllSidesAreEqual() throws TriangleException { + assertThat(new Triangle(2, 2, 2).isEquilateral()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("any side is unequal") - public void trianglesWithOneUnequalSideAreNotEquilateral() throws TriangleException { - Triangle triangle = new Triangle(2, 3, 2); - - assertThat(triangle.isEquilateral()).isFalse(); + @DisplayName("equilateral triangle -> any side is unequal") + public void equilateralTriangleAnySideIsUnequal() throws TriangleException { + assertThat(new Triangle(2, 3, 2).isEquilateral()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("no sides are equal") - public void trianglesWithNoEqualSidesAreNotEquilateral() throws TriangleException { - Triangle triangle = new Triangle(5, 4, 6); - - assertThat(triangle.isEquilateral()).isFalse(); + @DisplayName("equilateral triangle -> no sides are equal") + public void equilateralTriangleNoSidesAreEqual() throws TriangleException { + assertThat(new Triangle(5, 4, 6).isEquilateral()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("all zero sides is not a triangle") - public void trianglesWithNoSizeAreIllegal() { - assertThatExceptionOfType(TriangleException.class).isThrownBy(() -> new Triangle(0, 0, 0)); + @DisplayName("equilateral triangle -> all zero sides is not a triangle") + public void equilateralTriangleAllZeroSidesIsNotATriangle() throws TriangleException { + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle(0, 0, 0)); } @Disabled("Remove to run test") @Test - @DisplayName("sides may be floats") - public void verySmallTrianglesCanBeEquilateral() throws TriangleException { - Triangle triangle = new Triangle(0.5, 0.5, 0.5); - - assertThat(triangle.isEquilateral()).isTrue(); + @DisplayName("equilateral triangle -> sides may be floats") + public void equilateralTriangleSidesMayBeFloats() throws TriangleException { + assertThat(new Triangle(0.5, 0.5, 0.5).isEquilateral()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("last two sides are equal") - public void isoscelesTrianglesHaveLastTwoSidesEqual() throws TriangleException { - Triangle triangle = new Triangle(3, 4, 4); - - assertThat(triangle.isIsosceles()).isTrue(); + @DisplayName("isosceles triangle -> last two sides are equal") + public void isoscelesTriangleLastTwoSidesAreEqual() throws TriangleException { + assertThat(new Triangle(3, 4, 4).isIsosceles()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("first two sides are equal") - public void isoscelesTrianglesHaveTwoFirstSidesEqual() throws TriangleException { - Triangle triangle = new Triangle(4, 4, 3); - - assertThat(triangle.isIsosceles()).isTrue(); + @DisplayName("isosceles triangle -> first two sides are equal") + public void isoscelesTriangleFirstTwoSidesAreEqual() throws TriangleException { + assertThat(new Triangle(4, 4, 3).isIsosceles()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("first and last sides are equal") - public void isoscelesTrianglesHaveFirstAndLastSidesEqual() throws TriangleException { - Triangle triangle = new Triangle(4, 3, 4); - - assertThat(triangle.isIsosceles()).isTrue(); + @DisplayName("isosceles triangle -> first and last sides are equal") + public void isoscelesTriangleFirstAndLastSidesAreEqual() throws TriangleException { + assertThat(new Triangle(4, 3, 4).isIsosceles()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("equilateral triangles are also isosceles") - public void equilateralTrianglesAreAlsoIsosceles() throws TriangleException { - Triangle triangle = new Triangle(4, 4, 4); - - assertThat(triangle.isIsosceles()).isTrue(); + @DisplayName("isosceles triangle -> equilateral triangles are also isosceles") + public void isoscelesTriangleEquilateralTrianglesAreAlsoIsosceles() throws TriangleException { + assertThat(new Triangle(4, 4, 4).isIsosceles()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("no sides are equal") - public void noSidesAreEqualCantBeIsoceles() throws TriangleException { - Triangle triangle = new Triangle(2, 3, 4); - - assertThat(triangle.isIsosceles()).isFalse(); + @DisplayName("isosceles triangle -> no sides are equal") + public void isoscelesTriangleNoSidesAreEqual() throws TriangleException { + assertThat(new Triangle(2, 3, 4).isIsosceles()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("first triangle inequality violation") - public void firstTriangleInequalityViolation() { - assertThatExceptionOfType(TriangleException.class).isThrownBy(() -> new Triangle(1, 1, 3)); + @DisplayName("isosceles triangle -> first triangle inequality violation") + public void isoscelesTriangleFirstTriangleInequalityViolation() throws TriangleException { + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle(1, 1, 3)); } @Disabled("Remove to run test") @Test - @DisplayName("second triangle inequality violation") - public void secondTriangleInequalityViolation() { - assertThatExceptionOfType(TriangleException.class).isThrownBy(() -> new Triangle(1, 3, 1)); + @DisplayName("isosceles triangle -> second triangle inequality violation") + public void isoscelesTriangleSecondTriangleInequalityViolation() throws TriangleException { + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle(1, 3, 1)); } @Disabled("Remove to run test") @Test - @DisplayName("third triangle inequality violation") - public void thirdTriangleInequalityViolation() { - assertThatExceptionOfType(TriangleException.class).isThrownBy(() -> new Triangle(3, 1, 1)); + @DisplayName("isosceles triangle -> third triangle inequality violation") + public void isoscelesTriangleThirdTriangleInequalityViolation() throws TriangleException { + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle(3, 1, 1)); } @Disabled("Remove to run test") @Test - @DisplayName("sides may be floats") - public void verySmallTrianglesCanBeIsosceles() throws TriangleException { - Triangle triangle = new Triangle(0.5, 0.4, 0.5); - - assertThat(triangle.isIsosceles()).isTrue(); + @DisplayName("isosceles triangle -> sides may be floats") + public void isoscelesTriangleSidesMayBeFloats() throws TriangleException { + assertThat(new Triangle(0.5, 0.4, 0.5).isIsosceles()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("no sides are equal") - public void scaleneTrianglesHaveNoEqualSides() throws TriangleException { - Triangle triangle = new Triangle(5, 4, 6); - - assertThat(triangle.isScalene()).isTrue(); + @DisplayName("scalene triangle -> no sides are equal") + public void scaleneTriangleNoSidesAreEqual() throws TriangleException { + assertThat(new Triangle(5, 4, 6).isScalene()) + .isTrue(); } @Disabled("Remove to run test") @Test - @DisplayName("all sides are equal") - public void allSidesEqualAreNotScalene() throws TriangleException { - Triangle triangle = new Triangle(4, 4, 4); - - assertThat(triangle.isScalene()).isFalse(); + @DisplayName("scalene triangle -> all sides are equal") + public void scaleneTriangleAllSidesAreEqual() throws TriangleException { + assertThat(new Triangle(4, 4, 4).isScalene()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("first and second sides are equal") - public void twoSidesEqualAreNotScalene() throws TriangleException { - Triangle triangle = new Triangle(4, 4, 3); - - assertThat(triangle.isScalene()).isFalse(); + @DisplayName("scalene triangle -> first and second sides are equal") + public void scaleneTriangleFirstAndSecondSidesAreEqual() throws TriangleException { + assertThat(new Triangle(4, 4, 3).isScalene()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("first and third sides are equal") - public void firstAndThirdSidesAreEqualAreNotScalene() throws TriangleException { - Triangle triangle = new Triangle(3, 4, 3); - - assertThat(triangle.isScalene()).isFalse(); + @DisplayName("scalene triangle -> first and third sides are equal") + public void scaleneTriangleFirstAndThirdSidesAreEqual() throws TriangleException { + assertThat(new Triangle(3, 4, 3).isScalene()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("second and third sides are equal") - public void secondAndThirdSidesAreEqualAreNotScalene() throws TriangleException { - Triangle triangle = new Triangle(4, 3, 3); - - assertThat(triangle.isScalene()).isFalse(); + @DisplayName("scalene triangle -> second and third sides are equal") + public void scaleneTriangleSecondAndThirdSidesAreEqual() throws TriangleException { + assertThat(new Triangle(4, 3, 3).isScalene()) + .isFalse(); } @Disabled("Remove to run test") @Test - @DisplayName("may not violate triangle inequality") - public void mayNotViolateTriangleInequality() { - assertThatExceptionOfType(TriangleException.class).isThrownBy(() -> new Triangle(7, 3, 2)); + @DisplayName("scalene triangle -> may not violate triangle inequality") + public void scaleneTriangleMayNotViolateTriangleInequality() throws TriangleException { + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle(7, 3, 2)); } @Disabled("Remove to run test") @Test - @DisplayName("sides may be floats") - public void verySmallTrianglesCanBeScalene() throws TriangleException { - Triangle triangle = new Triangle(0.5, 0.4, 0.6); - - assertThat(triangle.isScalene()).isTrue(); + @DisplayName("scalene triangle -> sides may be floats") + public void scaleneTriangleSidesMayBeFloats() throws TriangleException { + assertThat(new Triangle(0.5, 0.4, 0.6).isScalene()) + .isTrue(); } + } diff --git a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java index a6827ee51..e8b6388fb 100644 --- a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java +++ b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,202 +5,255 @@ import static org.assertj.core.api.Assertions.assertThat; public class TwelveDaysTest { - private TwelveDays twelveDays; - @BeforeEach - public void setup() { - twelveDays = new TwelveDays(); - } + private TwelveDays twelveDays = new TwelveDays(); @Test - @DisplayName("first day a partridge in a pear tree") - public void testVerseOne() { - String expectedVerseOne = "On the first day of Christmas my true love gave to me: " + - "a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(1)).isEqualTo(expectedVerseOne); + @DisplayName("verse -> first day a partridge in a pear tree") + public void verseFirstDayAPartridgeInAPearTree() { + + assertThat(twelveDays.verse(1)) + .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + + "a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("second day two turtle doves") - public void testVerseTwo() { - String expectedVerseTwo = "On the second day of Christmas my true love gave to me: two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(2)).isEqualTo(expectedVerseTwo); + @DisplayName("verse -> second day two turtle doves") + public void verseSecondDayTwoTurtleDoves() { + + assertThat(twelveDays.verse(2)) + .isEqualTo("On the second day of Christmas my true love gave to me: two Turtle " + + "Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("third day three french hens") - public void testVerseThree() { - String expectedVerseThree = "On the third day of Christmas my true love gave to me: three French Hens, " + - "two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(3)).isEqualTo(expectedVerseThree); + @DisplayName("verse -> third day three french hens") + public void verseThirdDayThreeFrenchHens() { + + assertThat(twelveDays.verse(3)) + .isEqualTo("On the third day of Christmas my true love gave to me: three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("fourth day four calling birds") - public void testVerseFour() { - String expectedVerseFour = "On the fourth day of Christmas my true love gave to me: four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(4)).isEqualTo(expectedVerseFour); + @DisplayName("verse -> fourth day four calling birds") + public void verseFourthDayFourCallingBirds() { + + assertThat(twelveDays.verse(4)) + .isEqualTo("On the fourth day of Christmas my true love gave to me: four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("fifth day five gold rings") - public void testVerseFive() { - String expectedVerseFive = "On the fifth day of Christmas my true love gave to me: five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(5)).isEqualTo(expectedVerseFive); + @DisplayName("verse -> fifth day five gold rings") + public void verseFifthDayFiveGoldRings() { + + assertThat(twelveDays.verse(5)) + .isEqualTo("On the fifth day of Christmas my true love gave to me: five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("sixth day six geese-a-laying") - public void testVerseSix() { - String expectedVerseSix = "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, " + - "five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(6)).isEqualTo(expectedVerseSix); + @DisplayName("verse -> sixth day six geese-a-laying") + public void verseSixthDaySixGeeseALaying() { + + assertThat(twelveDays.verse(6)) + .isEqualTo("On the sixth day of Christmas my true love gave to me: six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("seventh day seven swans-a-swimming") - public void testVerseSeven() { - String expectedVerseSeven = "On the seventh day of Christmas my true love gave to me: " + - "seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, " + - "two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(7)).isEqualTo(expectedVerseSeven); + @DisplayName("verse -> seventh day seven swans-a-swimming") + public void verseSeventhDaySevenSwansASwimming() { + + assertThat(twelveDays.verse(7)) + .isEqualTo("On the seventh day of Christmas my true love gave to me: seven " + + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("eighth day eight maids-a-milking") - public void testVerseEight() { - String expectedVerseEight = "On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking," + - " seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(8)).isEqualTo(expectedVerseEight); + @DisplayName("verse -> eighth day eight maids-a-milking") + public void verseEighthDayEightMaidsAMilking() { + + assertThat(twelveDays.verse(8)) + .isEqualTo("On the eighth day of Christmas my true love gave to me: eight " + + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("ninth day nine ladies dancing") - public void testVerseNine() { - String expectedVerseNine = "On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, " + - "eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(9)).isEqualTo(expectedVerseNine); + @DisplayName("verse -> ninth day nine ladies dancing") + public void verseNinthDayNineLadiesDancing() { + + assertThat(twelveDays.verse(9)) + .isEqualTo("On the ninth day of Christmas my true love gave to me: nine Ladies " + + "Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("tenth day ten lords-a-leaping") - public void testVerseTen() { - String expectedVerseTen = "On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, " + - "nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, " + - "five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(10)).isEqualTo(expectedVerseTen); + @DisplayName("verse -> tenth day ten lords-a-leaping") + public void verseTenthDayTenLordsALeaping() { + + assertThat(twelveDays.verse(10)) + .isEqualTo("On the tenth day of Christmas my true love gave to me: ten " + + "Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven " + + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("eleventh day eleven pipers piping") - public void testVerseEleven() { - String expectedVerseEleven = "On the eleventh day of Christmas my true love gave to me: " + - "eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, " + - "seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(11)).isEqualTo(expectedVerseEleven); + @DisplayName("verse -> eleventh day eleven pipers piping") + public void verseEleventhDayElevenPipersPiping() { + + assertThat(twelveDays.verse(11)) + .isEqualTo("On the eleventh day of Christmas my true love gave to me: eleven " + + "Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight " + + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("twelfth day twelve drummers drumming") - public void testVerseTwelve() { - String expectedVerseTwelve = "On the twelfth day of Christmas my true love gave to me: " + - "twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, " + - "eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verse(12)).isEqualTo(expectedVerseTwelve); + @DisplayName("verse -> twelfth day twelve drummers drumming") + public void verseTwelfthDayTwelveDrummersDrumming() { + + assertThat(twelveDays.verse(12)) + .isEqualTo("On the twelfth day of Christmas my true love gave to me: twelve " + + "Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine " + + "Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("recites first three verses of the song") - public void testFirstThreeVerses() { - String expectedVersesOneToThree = "On the first day of Christmas my true love gave to me: " + - "a Partridge in a Pear Tree.\n\n" + - "On the second day of Christmas my true love gave to me: two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n\n" + - "On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verses(1, 3)).isEqualTo(expectedVersesOneToThree); + @DisplayName("lyrics -> recites first three verses of the song") + public void lyricsRecitesFirstThreeVersesOfTheSong() { + + assertThat(twelveDays.verses(1, 3)) + .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + + "a Pear Tree.\n" + + "\n" + + "On the second day of Christmas my true love gave to me: two Turtle " + + "Doves, and a Partridge in a Pear Tree.\n" + + "\n" + + "On the third day of Christmas my true love gave to me: three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("recites three verses from the middle of the song") - public void testFourthToSixthVerses() { - String expectedVersesFourToSix = "On the fourth day of Christmas my true love gave to me: " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + - "On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + - "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.verses(4, 6)).isEqualTo(expectedVersesFourToSix); + @DisplayName("lyrics -> recites three verses from the middle of the song") + public void lyricsRecitesThreeVersesFromTheMiddleOfTheSong() { + + assertThat(twelveDays.verses(4, 6)) + .isEqualTo("On the fourth day of Christmas my true love gave to me: four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n" + + "\n" + + "On the fifth day of Christmas my true love gave to me: five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n" + + "\n" + + "On the sixth day of Christmas my true love gave to me: six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } @Disabled("Remove to run test") @Test - @DisplayName("recites the whole song") - public void testSingWholeSong() { - String expectedSong = "On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.\n" + - "\n" + - "On the second day of Christmas my true love gave to me: two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n" + - "\n" + - "On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n" + - "\n" + - "On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, " + - "two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, " + - "six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n" + - "\n" + - "On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, " + - "seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking," + - " seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing," + - " eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, " + - "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + - "\n" + - "On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, " + - "ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, " + - "six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, " + - "and a Partridge in a Pear Tree.\n" + - "\n" + - "On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, " + - "eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, " + - "seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, " + - "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; - assertThat(twelveDays.sing()).isEqualTo(expectedSong); + @DisplayName("lyrics -> recites the whole song") + public void lyricsRecitesTheWholeSong() { + + assertThat(twelveDays.sing()) + .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + + "a Pear Tree.\n" + + "\n" + + "On the second day of Christmas my true love gave to me: two Turtle " + + "Doves, and a Partridge in a Pear Tree.\n" + + "\n" + + "On the third day of Christmas my true love gave to me: three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + + "\n" + + "On the fourth day of Christmas my true love gave to me: four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n" + + "\n" + + "On the fifth day of Christmas my true love gave to me: five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n" + + "\n" + + "On the sixth day of Christmas my true love gave to me: six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + + "\n" + + "On the seventh day of Christmas my true love gave to me: seven " + + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n" + + "\n" + + "On the eighth day of Christmas my true love gave to me: eight " + + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n" + + "\n" + + "On the ninth day of Christmas my true love gave to me: nine Ladies " + + "Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" + + "\n" + + "On the tenth day of Christmas my true love gave to me: ten " + + "Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven " + + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + + "Tree.\n" + + "\n" + + "On the eleventh day of Christmas my true love gave to me: eleven " + + "Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight " + + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + + "Partridge in a Pear Tree.\n" + + "\n" + + "On the twelfth day of Christmas my true love gave to me: twelve " + + "Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine " + + "Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); + } + } diff --git a/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java b/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java index 80d39f0ac..29c144bd7 100644 --- a/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java +++ b/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java @@ -9,9 +9,14 @@ public class TwoBucketTest { @Test @DisplayName("Measure using bucket one of size 3 and bucket two of size 5 - start with bucket one") - public void testBucketOneSizeThreeBucketTwoSizeFiveStartWithOne() { + public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketOne() { - Result bucketResult = new TwoBucket(3, 5, 1, "one").getResult(); + Result bucketResult = new TwoBucket( + 3, + 5, + 1, + "one" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(4); assertThat(bucketResult.getFinalBucket()).isEqualTo("one"); @@ -22,9 +27,14 @@ public void testBucketOneSizeThreeBucketTwoSizeFiveStartWithOne() { @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 3 and bucket two of size 5 - start with bucket two") - public void testBucketOneSizeThreeBucketTwoSizeFiveStartWithTwo() { + public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketTwo() { - Result bucketResult = new TwoBucket(3, 5, 1, "two").getResult(); + Result bucketResult = new TwoBucket( + 3, + 5, + 1, + "two" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(8); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); @@ -35,9 +45,14 @@ public void testBucketOneSizeThreeBucketTwoSizeFiveStartWithTwo() { @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 7 and bucket two of size 11 - start with bucket one") - public void testBucketOneSizeSevenBucketTwoSizeElevenStartWithOne() { + public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketOn() { - Result bucketResult = new TwoBucket(7, 11, 2, "one").getResult(); + Result bucketResult = new TwoBucket( + 7, + 11, + 2, + "one" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(14); assertThat(bucketResult.getFinalBucket()).isEqualTo("one"); @@ -48,9 +63,14 @@ public void testBucketOneSizeSevenBucketTwoSizeElevenStartWithOne() { @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 7 and bucket two of size 11 - start with bucket two") - public void testBucketOneSizeSevenBucketTwoSizeElevenStartWithTwo() { + public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketTw() { - Result bucketResult = new TwoBucket(7, 11, 2, "two").getResult(); + Result bucketResult = new TwoBucket( + 7, + 11, + 2, + "two" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(18); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); @@ -60,10 +80,16 @@ public void testBucketOneSizeSevenBucketTwoSizeElevenStartWithTwo() { @Disabled("Remove to run test") @Test - @DisplayName("Measure one step using bucket one of size 1 and bucket two of size 3 - start with bucket two") - public void testBucketOneSizeOneBucketTwoSizeThreeStartWithTwo() { + @DisplayName("Measure one step using bucket one of size 1 and bucket two of size 3 - " + + "start with bucket two") + public void measureOneStepUsingBucketOneOfSize1AndBucketTwoOfSize3StartWithBu() { - Result bucketResult = new TwoBucket(1, 3, 3, "two").getResult(); + Result bucketResult = new TwoBucket( + 1, + 3, + 3, + "two" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(1); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); @@ -73,13 +99,16 @@ public void testBucketOneSizeOneBucketTwoSizeThreeStartWithTwo() { @Disabled("Remove to run test") @Test - @DisplayName( - "Measure using bucket one of size 2 and bucket two of size 3 - " + - "start with bucket one and end with bucket two" - ) - public void testBucketOneSizeTwoBucketTwoSizeThreeStartWithOne() { + @DisplayName("Measure using bucket one of size 2 and bucket two of size 3 - start " + + "with bucket one and end with bucket two") + public void measureUsingBucketOneOfSize2AndBucketTwoOfSize3StartWithBucketOne() { - Result bucketResult = new TwoBucket(2, 3, 3, "one").getResult(); + Result bucketResult = new TwoBucket( + 2, + 3, + 3, + "one" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(2); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); @@ -87,48 +116,32 @@ public void testBucketOneSizeTwoBucketTwoSizeThreeStartWithOne() { } - @Disabled("Remove to run test") - @Test - @DisplayName("Measure using bucket one much bigger than bucket two") - public void testBucketOneMuchBiggerThanBucketTwo() { - - Result bucketResult = new TwoBucket(5, 1, 2, "one").getResult(); - - assertThat(bucketResult.getTotalMoves()).isEqualTo(6); - assertThat(bucketResult.getFinalBucket()).isEqualTo("one"); - assertThat(bucketResult.getOtherBucket()).isEqualTo(1); - - } - - @Disabled("Remove to run test") - @Test - @DisplayName("Measure using bucket one much smaller than bucket two") - public void testBucketOneMuchSmallerThanBucketTwo() { - - Result bucketResult = new TwoBucket(3, 15, 9, "one").getResult(); - - assertThat(bucketResult.getTotalMoves()).isEqualTo(6); - assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); - assertThat(bucketResult.getOtherBucket()).isEqualTo(0); - - } - @Disabled("Remove to run test") @Test @DisplayName("Not possible to reach the goal") - public void testReachingGoalIsImpossible() { + public void notPossibleToReachTheGoal() { assertThatExceptionOfType(UnreachableGoalException.class) - .isThrownBy(() -> new TwoBucket(6, 15, 5, "one").getResult()); + .isThrownBy(() -> new TwoBucket( + 6, + 15, + 5, + "one" + ).getResult()); } @Disabled("Remove to run test") @Test @DisplayName("With the same buckets but a different goal, then it is possible") - public void testBucketOneSizeSixBucketTwoSizeFifteenStartWithOne() { + public void withTheSameBucketsButADifferentGoalThenItIsPossible() { - Result bucketResult = new TwoBucket(6, 15, 9, "one").getResult(); + Result bucketResult = new TwoBucket( + 6, + 15, + 9, + "one" + ).getResult(); assertThat(bucketResult.getTotalMoves()).isEqualTo(10); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); @@ -139,10 +152,16 @@ public void testBucketOneSizeSixBucketTwoSizeFifteenStartWithOne() { @Disabled("Remove to run test") @Test @DisplayName("Goal larger than both buckets is impossible") - public void testGoalLargerThanBothBucketsIsImpossible() { + public void goalLargerThanBothBucketsIsImpossible() { assertThatExceptionOfType(UnreachableGoalException.class) - .isThrownBy(() -> new TwoBucket(5, 7, 8, "one").getResult()); + .isThrownBy(() -> new TwoBucket( + 5, + 7, + 8, + "one" + ).getResult()); } + } diff --git a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java index 5e3059937..f6b10f5fe 100644 --- a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java +++ b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java @@ -2,7 +2,6 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -10,325 +9,347 @@ public class VariableLengthQuantityTest { - private VariableLengthQuantity variableLengthQuantity = - new VariableLengthQuantity(); + private VariableLengthQuantity variableLengthQuantity = new VariableLengthQuantity(); @Test - @DisplayName("zero") - public void testZero() { - List expected = Arrays.asList("0x0"); - List numbers = Arrays.asList(0x0L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> zero") + public void encodeASeriesOfIntegersProducingASeriesOfBytesZero() { - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); - } + assertThat(variableLengthQuantity.encode(List.of(0x0L))) + .isEqualTo(List.of("0x0")); - @Disabled("Remove to run test") - @Test - @DisplayName("arbitrary single byte") - public void testArbitrarySingleByte() { - List expected = Arrays.asList("0x40"); - List numbers = Arrays.asList(0x40L); - - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("asymmetric single byte") - public void testAsymmetricSingleByte() { - List expected = Arrays.asList("0x53"); - List numbers = Arrays.asList(0x53L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary single byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitrarySingleByte() { - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); - } + assertThat(variableLengthQuantity.encode(List.of(0x40L))) + .isEqualTo(List.of("0x40")); - @Disabled("Remove to run test") - @Test - @DisplayName("largest single byte") - public void testLargestSingleByte() { - List expected = Arrays.asList("0x7f"); - List numbers = Arrays.asList(0x7fL); - - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("smallest double byte") - public void testSmallestDoubleByte() { - List expected = Arrays.asList("0x81", "0x0"); - List numbers = Arrays.asList(0x80L); - - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); - } + @DisplayName("Encode a series of integers, producing a series of bytes. -> largest single byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestSingleByte() { - @Disabled("Remove to run test") - @Test - @DisplayName("arbitrary double byte") - public void testArbitraryDoubleByte() { - List expected = Arrays.asList("0xc0", "0x0"); - List numbers = Arrays.asList(0x2000L); + assertThat(variableLengthQuantity.encode(List.of(0x7fL))) + .isEqualTo(List.of("0x7f")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("asymmetric double byte") - public void testAsymmetricDoubleByte() { - List expected = Arrays.asList("0x81", "0x2d"); - List numbers = Arrays.asList(0xadL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest double byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestDoubleByte() { - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); - } + assertThat(variableLengthQuantity.encode(List.of(0x80L))) + .isEqualTo(List.of("0x81", "0x0")); - @Disabled("Remove to run test") - @Test - @DisplayName("largest double byte") - public void testLargestDoubleByte() { - List expected = Arrays.asList("0xff", "0x7f"); - List numbers = Arrays.asList(0x3fffL); - - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("smallest triple byte") - public void testSmallestTripleByte() { - List expected = Arrays.asList("0x81", "0x80", "0x0"); - List numbers = Arrays.asList(0x4000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary double byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryDoubleByte() { + + assertThat(variableLengthQuantity.encode(List.of(0x2000L))) + .isEqualTo(List.of("0xc0", "0x0")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("arbitrary triple byte") - public void testArbitraryTripleByte() { - List expected = Arrays.asList("0xc0", "0x80", "0x0"); - List numbers = Arrays.asList(0x100000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> largest double byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestDoubleByte() { + + assertThat(variableLengthQuantity.encode(List.of(0x3fffL))) + .isEqualTo(List.of("0xff", "0x7f")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("asymmetric triple byte") - public void testAsymmetricTripleByte() { - List expected = Arrays.asList("0x87", "0xab", "0x1c"); - List numbers = Arrays.asList(0x1d59cL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest triple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestTripleByte() { + + assertThat(variableLengthQuantity.encode(List.of(0x4000L))) + .isEqualTo(List.of("0x81", "0x80", "0x0")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("largest triple byte") - public void testLargestTripleByte() { - List expected = Arrays.asList("0xff", "0xff", "0x7f"); - List numbers = Arrays.asList(0x1fffffL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary triple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryTripleByte() { + + assertThat(variableLengthQuantity.encode(List.of(0x100000L))) + .isEqualTo(List.of("0xc0", "0x80", "0x0")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("smallest quadruple byte") - public void testSmallestQuadrupleByte() { - List expected = Arrays.asList("0x81", "0x80", "0x80", "0x0"); - List numbers = Arrays.asList(0x200000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> largest triple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestTripleByte() { + + assertThat(variableLengthQuantity.encode(List.of(0x1fffffL))) + .isEqualTo(List.of("0xff", "0xff", "0x7f")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("arbitrary quadruple byte") - public void testArbitraryQuadrupleByte() { - List expected = Arrays.asList("0xc0", "0x80", "0x80", "0x0"); - List numbers = Arrays.asList(0x8000000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest quadruple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestQuadrupleBy() { + + assertThat(variableLengthQuantity.encode(List.of(0x200000L))) + .isEqualTo(List.of("0x81", "0x80", "0x80", "0x0")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("asymmetric quadruple byte") - public void testAsymmetricQuadrupleByte() { - List expected = Arrays.asList("0x81", "0xd5", "0xee", "0x4"); - List numbers = Arrays.asList(0x357704L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary quadruple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuadrupleB() { + + assertThat(variableLengthQuantity.encode(List.of(0x8000000L))) + .isEqualTo(List.of("0xc0", "0x80", "0x80", "0x0")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("largest quadruple byte") - public void testLargestQuadrupleByte() { - List expected = Arrays.asList("0xff", "0xff", "0xff", "0x7f"); - List numbers = Arrays.asList(0xfffffffL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> largest quadruple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestQuadrupleByt() { + + assertThat(variableLengthQuantity.encode(List.of(0xfffffffL))) + .isEqualTo(List.of("0xff", "0xff", "0xff", "0x7f")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("smallest quintuple byte") - public void testSmallestQuintupleByte() { - List expected = Arrays.asList("0x81", "0x80", "0x80", "0x80", "0x0"); - List numbers = Arrays.asList(0x10000000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest quintuple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestQuintupleBy() { + + assertThat(variableLengthQuantity.encode(List.of(0x10000000L))) + .isEqualTo(List.of( + "0x81", + "0x80", + "0x80", + "0x80", + "0x0" + )); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("arbitrary quintuple byte") - public void testArbitraryQuintupleByte() { - List expected = Arrays.asList("0x8f", "0xf8", "0x80", "0x80", "0x0"); - List numbers = Arrays.asList(0xff000000L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary quintuple byte") + public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuintupleB() { + + assertThat(variableLengthQuantity.encode(List.of(0xff000000L))) + .isEqualTo(List.of( + "0x8f", + "0xf8", + "0x80", + "0x80", + "0x0" + )); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("asymmetric quintuple byte") - public void testAsymmetricQuintupleByte() { - List expected = Arrays.asList("0x88", "0xb3", "0x95", "0xc2", "0x5"); - List numbers = Arrays.asList(0x86656105L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> maximum " + + "32-bit integer input") + public void encodeASeriesOfIntegersProducingASeriesOfBytesMaximum32BitInteger() { + + assertThat(variableLengthQuantity.encode(List.of(0xffffffffL))) + .isEqualTo(List.of( + "0x8f", + "0xff", + "0xff", + "0xff", + "0x7f" + )); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("maximum 32-bit integer input") - public void testMaximum32BitIntegerInput() { - List expected = Arrays.asList("0x8f", "0xff", "0xff", "0xff", "0x7f"); - List numbers = Arrays.asList(0xffffffffL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> two single-byte values") + public void encodeASeriesOfIntegersProducingASeriesOfBytesTwoSingleByteValues() { + + assertThat(variableLengthQuantity.encode(List.of(0x40L, 0x7fL))) + .isEqualTo(List.of("0x40", "0x7f")); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("two single-byte values") - public void testTwoSingleByteValues() { - List expected = Arrays.asList("0x40", "0x7f"); - List numbers = Arrays.asList(0x40L, 0x7fL); + @DisplayName("Encode a series of integers, producing a series of bytes. -> two multi-byte values") + public void encodeASeriesOfIntegersProducingASeriesOfBytesTwoMultiByteValues() { + + assertThat(variableLengthQuantity.encode(List.of(0x4000L, 0x123456L))) + .isEqualTo(List.of( + "0x81", + "0x80", + "0x0", + "0xc8", + "0xe8", + "0x56" + )); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("two multi-byte values") - public void testTwoMultiByteValues() { - List expected = Arrays.asList("0x81", "0x80", "0x0", "0xc8", "0xe8", "0x56"); - List numbers = Arrays.asList(0x4000L, 0x123456L); + @DisplayName("Encode a series of integers, producing a series of bytes. -> many multi-byte values") + public void encodeASeriesOfIntegersProducingASeriesOfBytesManyMultiByteValues() { + + assertThat(variableLengthQuantity.encode(List.of( + 0x2000L, + 0x123456L, + 0xfffffffL, + 0x0L, + 0x3fffL, + 0x4000L + ))) + .isEqualTo(List.of( + "0xc0", + "0x0", + "0xc8", + "0xe8", + "0x56", + "0xff", + "0xff", + "0xff", + "0x7f", + "0x0", + "0xff", + "0x7f", + "0x81", + "0x80", + "0x0" + )); - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("many multi-byte values") - public void testManyMultiByteValues() { - List expected = Arrays.asList("0xc0", "0x0", "0xc8", "0xe8", - "0x56", "0xff", "0xff", "0xff", - "0x7f", "0x0", "0xff", "0x7f", - "0x81", "0x80", "0x0"); - List numbers = Arrays.asList(0x2000L, 0x123456L, 0xfffffffL, - 0x0L, 0x3fffL, 0x4000L); - - assertThat(variableLengthQuantity.encode(numbers)).isEqualTo(expected); - } + @DisplayName("Decode a series of bytes, producing a series of integers. -> one byte") + public void decodeASeriesOfBytesProducingASeriesOfIntegersOneByte() { - @Disabled("Remove to run test") - @Test - @DisplayName("one byte") - public void testDecodeOneByte() { - List expected = Arrays.asList("0x7f"); - List bytes = Arrays.asList(0x7fL); + assertThat(variableLengthQuantity.decode(List.of(0x7fL))) + .isEqualTo(List.of("0x7f")); - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("two bytes") - public void testDecodeTwoBytes() { - List expected = Arrays.asList("0x2000"); - List bytes = Arrays.asList(0xc0L, 0x0L); + @DisplayName("Decode a series of bytes, producing a series of integers. -> two bytes") + public void decodeASeriesOfBytesProducingASeriesOfIntegersTwoBytes() { + + assertThat(variableLengthQuantity.decode(List.of(0xc0L, 0x0L))) + .isEqualTo(List.of("0x2000")); - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("three bytes") - public void testDecodeThreeBytes() { - List expected = Arrays.asList("0x1fffff"); - List bytes = Arrays.asList(0xffL, 0xffL, 0x7fL); + @DisplayName("Decode a series of bytes, producing a series of integers. -> three bytes") + public void decodeASeriesOfBytesProducingASeriesOfIntegersThreeBytes() { + + assertThat(variableLengthQuantity.decode(List.of(0xffL, 0xffL, 0x7fL))) + .isEqualTo(List.of("0x1fffff")); - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("four bytes") - public void testDecodeFourBytes() { - List expected = Arrays.asList("0x200000"); - List bytes = Arrays.asList(0x81L, 0x80L, 0x80L, 0x0L); + @DisplayName("Decode a series of bytes, producing a series of integers. -> four bytes") + public void decodeASeriesOfBytesProducingASeriesOfIntegersFourBytes() { + + assertThat(variableLengthQuantity.decode(List.of(0x81L, 0x80L, 0x80L, 0x0L))) + .isEqualTo(List.of("0x200000")); - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("maximum 32-bit integer") - public void testDecodeMaximum32BitInteger() { - List expected = Arrays.asList("0xffffffff"); - List bytes = Arrays.asList(0x8fL, 0xffL, 0xffL, 0xffL, 0x7fL); + @DisplayName("Decode a series of bytes, producing a series of integers. -> maximum 32-bit integer") + public void decodeASeriesOfBytesProducingASeriesOfIntegersMaximum32BitInteger() { + + assertThat(variableLengthQuantity.decode(List.of( + 0x8fL, + 0xffL, + 0xffL, + 0xffL, + 0x7fL + ))) + .isEqualTo(List.of("0xffffffff")); - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); } @Disabled("Remove to run test") @Test - @DisplayName("incomplete sequence causes error") - public void testCannotDecodeIncompleteSequence() { - List bytes = Arrays.asList(0xffL); + @DisplayName("Decode a series of bytes, producing a series of integers. -> " + + "incomplete sequence causes error") + public void decodeASeriesOfBytesProducingASeriesOfIntegersIncompleteSequenceC() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> variableLengthQuantity.decode(bytes)) + .isThrownBy(() -> variableLengthQuantity.decode(List.of(0xffL))) .withMessage("Invalid variable-length quantity encoding"); + } @Disabled("Remove to run test") @Test - @DisplayName("incomplete sequence causes error, even if value is zero") - public void testCannotDecodeIncompleteSequenceEvenIfValueIsZero() { - List bytes = Arrays.asList(0x80L); + @DisplayName("Decode a series of bytes, producing a series of integers. -> " + + "incomplete sequence causes error, even if value is zero") + public void decodeASeriesOfBytesProducingASeriesOfIntegersIncompleteSequenceC2() { assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> variableLengthQuantity.decode(bytes)) + .isThrownBy(() -> variableLengthQuantity.decode(List.of(0x80L))) .withMessage("Invalid variable-length quantity encoding"); + } @Disabled("Remove to run test") @Test - @DisplayName("multiple values") - public void testDecodeMultipleBytes() { - List expected = Arrays.asList("0x2000", "0x123456", - "0xfffffff", "0x0", "0x3fff", - "0x4000"); - List bytes = Arrays.asList(0xc0L, 0x0L, 0xc8L, 0xe8L, 0x56L, - 0xffL, 0xffL, 0xffL, 0x7fL, 0x0L, - 0xffL, 0x7fL, 0x81L, 0x80L, 0x0L); - - assertThat(variableLengthQuantity.decode(bytes)).isEqualTo(expected); + @DisplayName("Decode a series of bytes, producing a series of integers. -> multiple values") + public void decodeASeriesOfBytesProducingASeriesOfIntegersMultipleValues() { + + assertThat(variableLengthQuantity.decode(List.of( + 0xc0L, + 0x0L, + 0xc8L, + 0xe8L, + 0x56L, + 0xffL, + 0xffL, + 0xffL, + 0x7fL, + 0x0L, + 0xffL, + 0x7fL, + 0x81L, + 0x80L, + 0x0L + ))) + .isEqualTo(List.of( + "0x2000", + "0x123456", + "0xfffffff", + "0x0", + "0x3fff", + "0x4000" + )); + } + } diff --git a/exercises/practice/word-count/src/test/java/WordCountTest.java b/exercises/practice/word-count/src/test/java/WordCountTest.java index 0c2cd4e01..e3bbefae1 100644 --- a/exercises/practice/word-count/src/test/java/WordCountTest.java +++ b/exercises/practice/word-count/src/test/java/WordCountTest.java @@ -1,204 +1,159 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class WordCountTest { - private WordCount wordCount; - private Map actualWordCount; - private Map expectedWordCount; - - @BeforeEach - public void setup() { - wordCount = new WordCount(); - expectedWordCount = new HashMap<>(); - } - - @Test @DisplayName("count one word") public void countOneWord() { - expectedWordCount.put("word", 1); - - actualWordCount = wordCount.phrase("word"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("word")) + .isEqualTo(Map.of("word", 1)); } @Disabled("Remove to run test") @Test @DisplayName("count one of each word") public void countOneOfEachWord() { - expectedWordCount.put("one", 1); - expectedWordCount.put("of", 1); - expectedWordCount.put("each", 1); - - actualWordCount = wordCount.phrase("one of each"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("one of each")) + .isEqualTo(Map.of("one", 1, "of", 1, "each", 1)); } @Disabled("Remove to run test") @Test @DisplayName("multiple occurrences of a word") public void multipleOccurrencesOfAWord() { - expectedWordCount.put("one", 1); - expectedWordCount.put("fish", 4); - expectedWordCount.put("two", 1); - expectedWordCount.put("red", 1); - expectedWordCount.put("blue", 1); - - actualWordCount = wordCount.phrase("one fish two fish red fish blue fish"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("one fish two fish red fish blue fish")) + .isEqualTo(Map.of( + "one", 1, + "fish", 4, + "two", 1, + "red", 1, + "blue", 1 + )); } @Disabled("Remove to run test") @Test @DisplayName("handles cramped lists") public void handlesCrampedLists() { - expectedWordCount.put("one", 1); - expectedWordCount.put("two", 1); - expectedWordCount.put("three", 1); - - actualWordCount = wordCount.phrase("one,two,three"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("one,two,three")) + .isEqualTo(Map.of("one", 1, "two", 1, "three", 1)); } @Disabled("Remove to run test") @Test @DisplayName("handles expanded lists") public void handlesExpandedLists() { - expectedWordCount.put("one", 1); - expectedWordCount.put("two", 1); - expectedWordCount.put("three", 1); - - actualWordCount = wordCount.phrase("one,\ntwo,\nthree"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("one,\ntwo,\nthree")) + .isEqualTo(Map.of("one", 1, "two", 1, "three", 1)); } @Disabled("Remove to run test") @Test @DisplayName("ignore punctuation") public void ignorePunctuation() { - expectedWordCount.put("car", 1); - expectedWordCount.put("carpet", 1); - expectedWordCount.put("as", 1); - expectedWordCount.put("java", 1); - expectedWordCount.put("javascript", 1); - - actualWordCount = wordCount.phrase("car : carpet as java : javascript!!&@$%^&"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); - + assertThat(new WordCount().phrase("car: carpet as java: javascript!!&@$%^&")) + .isEqualTo(Map.of( + "car", 1, + "carpet", 1, + "as", 1, + "java", 1, + "javascript", 1 + )); } @Disabled("Remove to run test") @Test @DisplayName("include numbers") public void includeNumbers() { - expectedWordCount.put("testing", 2); - expectedWordCount.put("1", 1); - expectedWordCount.put("2", 1); - - actualWordCount = wordCount.phrase("testing, 1, 2 testing"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("testing, 1, 2 testing")) + .isEqualTo(Map.of("testing", 2, "1", 1, "2", 1)); } @Disabled("Remove to run test") @Test @DisplayName("normalize case") public void normalizeCase() { - expectedWordCount.put("go", 3); - expectedWordCount.put("stop", 2); - - actualWordCount = wordCount.phrase("go Go GO Stop stop"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("go Go GO Stop stop")) + .isEqualTo(Map.of("go", 3, "stop", 2)); } @Disabled("Remove to run test") @Test @DisplayName("with apostrophes") public void withApostrophes() { - expectedWordCount.put("first", 1); - expectedWordCount.put("don't", 2); - expectedWordCount.put("laugh", 1); - expectedWordCount.put("then", 1); - expectedWordCount.put("cry", 1); - expectedWordCount.put("you're", 1); - expectedWordCount.put("getting", 1); - expectedWordCount.put("it", 1); - - actualWordCount = wordCount.phrase("'First: don't laugh. Then: don't cry. You're getting it.'"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("'First: don't laugh. Then: don't cry. You're getting it.'")) + .isEqualTo(Map.of( + "first", 1, + "don't", 2, + "laugh", 1, + "then", 1, + "cry", 1, + "you're", 1, + "getting", 1, + "it", 1 + )); } @Disabled("Remove to run test") @Test @DisplayName("with quotations") public void withQuotations() { - expectedWordCount.put("joe", 1); - expectedWordCount.put("can't", 1); - expectedWordCount.put("tell", 1); - expectedWordCount.put("between", 1); - expectedWordCount.put("large", 2); - expectedWordCount.put("and", 1); - - actualWordCount = wordCount.phrase("Joe can't tell between 'large' and large."); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("Joe can't tell between 'large' and large.")) + .isEqualTo(Map.of( + "joe", 1, + "can't", 1, + "tell", 1, + "between", 1, + "large", 2, + "and", 1 + )); } @Disabled("Remove to run test") @Test @DisplayName("substrings from the beginning") public void substringsFromTheBeginning() { - expectedWordCount.put("joe", 1); - expectedWordCount.put("can't", 1); - expectedWordCount.put("tell", 1); - expectedWordCount.put("between", 1); - expectedWordCount.put("app", 1); - expectedWordCount.put("apple", 1); - expectedWordCount.put("and", 1); - expectedWordCount.put("a", 1); - - actualWordCount = wordCount.phrase("Joe can't tell between app, apple and a."); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("Joe can't tell between app, apple and a.")) + .isEqualTo(Map.of( + "joe", 1, + "can't", 1, + "tell", 1, + "between", 1, + "app", 1, + "apple", 1, + "and", 1, + "a", 1 + )); } @Disabled("Remove to run test") @Test @DisplayName("multiple spaces not detected as a word") public void multipleSpacesNotDetectedAsAWord() { - expectedWordCount.put("multiple", 1); - expectedWordCount.put("whitespaces", 1); - - actualWordCount = wordCount.phrase(" multiple whitespaces"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase(" multiple whitespaces")) + .isEqualTo(Map.of("multiple", 1, "whitespaces", 1)); } @Disabled("Remove to run test") @Test @DisplayName("alternating word separators not detected as a word") - public void alternatingWordSeperatorsNotDetectedAsAWord() { - expectedWordCount.put("one", 1); - expectedWordCount.put("two", 1); - expectedWordCount.put("three", 1); - - actualWordCount = wordCount.phrase(",\n,one,\n ,two \n 'three'"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + public void alternatingWordSeparatorsNotDetectedAsAWord() { + assertThat(new WordCount().phrase(",\n,one,\n ,two \n 'three'")) + .isEqualTo(Map.of("one", 1, "two", 1, "three", 1)); } @Disabled("Remove to run test") @Test @DisplayName("quotation for word with apostrophe") public void quotationForWordWithApostrophe() { - expectedWordCount.put("can", 1); - expectedWordCount.put("can't", 2); - - actualWordCount = wordCount.phrase("can, can't, 'can't'"); - assertThat(actualWordCount).isEqualTo(expectedWordCount); + assertThat(new WordCount().phrase("can, can't, 'can't'")) + .isEqualTo(Map.of("can", 1, "can't", 2)); } } diff --git a/exercises/practice/word-search/src/test/java/WordSearcherTest.java b/exercises/practice/word-search/src/test/java/WordSearcherTest.java index 3a7d9291e..843ac888c 100644 --- a/exercises/practice/word-search/src/test/java/WordSearcherTest.java +++ b/exercises/practice/word-search/src/test/java/WordSearcherTest.java @@ -1,4 +1,3 @@ -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -12,606 +11,713 @@ public class WordSearcherTest { - private WordSearcher wordSearcher; - - @BeforeEach - public void setUp() { - wordSearcher = new WordSearcher(); - } - @Test @DisplayName("Should accept an initial game grid and a target search word") - public void testAcceptsInitialGridAndTargetWord() { + public void shouldAcceptAnInitialGameGridAndATargetSearchWord() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"jefblpepre".toCharArray()}; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); expectedLocations.put("clojure", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'} - } - ); - + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate one word written left to right") - public void testLocatesOneWordWrittenLeftToRight() { + public void shouldLocateOneWordWrittenLeftToRight() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"clojurermt".toCharArray()}; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 1), new Pair(7, 1)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(7, 1) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate the same word written left to right in a different position") - public void testShouldLocateTheSameWordLeftToRightInDifferentPosition() { + public void shouldLocateTheSameWordWrittenLeftToRightInADifferentPosition() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"mtclojurer".toCharArray()}; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(3, 1), new Pair(9, 1)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'m', 't', 'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(3, 1), + new Pair(9, 1) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a different left to right word") - public void testShouldLocateADifferentLeftToRightWord() { + public void shouldLocateADifferentLeftToRightWord() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"coffeelplx".toCharArray()}; + Set wordsToSearchFor = Set.of("coffee"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("coffee", Optional.of(new WordLocation(new Pair(1, 1), new Pair(6, 1)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'c', 'o', 'f', 'f', 'e', 'e', 'l', 'p', 'l', 'x'} - } - ); - + expectedLocations.put("coffee", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(6, 1) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate that different left to right word in a different position") - public void testShouldLocateThatDifferentLeftToRightWordInADifferentPosition() { + public void shouldLocateThatDifferentLeftToRightWordInADifferentPosition() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"xcoffeezlp".toCharArray()}; + Set wordsToSearchFor = Set.of("coffee"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("coffee", Optional.of(new WordLocation(new Pair(2, 1), new Pair(7, 1)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'x', 'c', 'o', 'f', 'f', 'e', 'e', 'z', 'l', 'p'} - } - ); - + expectedLocations.put("coffee", Optional.of(new WordLocation( + new Pair(2, 1), + new Pair(7, 1) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a left to right word in two line grid") - public void testShouldLocateLeftToRightWordInTwoLineGrid() { + public void shouldLocateALeftToRightWordInTwoLineGrid() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"jefblpepre".toCharArray(), "tclojurerm".toCharArray()}; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(2, 2), new Pair(8, 2)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'t', 'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(2, 2), + new Pair(8, 2) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a left to right word in three line grid") - public void testShouldLocateLeftToRightWordInThreeLineGrid() { + public void shouldLocateALeftToRightWordInThreeLineGrid() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "camdcimgtc".toCharArray(), + "jefblpepre".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 3), new Pair(7, 3)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 3), + new Pair(7, 3) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a left to right word in ten line grid") - public void testLocatesWordWrittenLeftToRightInTenLineGrid() { + public void shouldLocateALeftToRightWordInTenLineGrid() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate that left to right word in a different position in a ten line grid") - public void testLocatesSameWordWrittenLeftToRightInDifferentTenLineGrid() { + public void shouldLocateThatLeftToRightWordInADifferentPositionInATenLineGrid() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "clojurermt".toCharArray(), + "jalaycalmp".toCharArray() + }; + Set wordsToSearchFor = Set.of("clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 9), new Pair(7, 9)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 9), + new Pair(7, 9) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a different left to right word in a ten line grid") - public void testLocatesDifferentWordWrittenLeftToRightInTenLineGrid() { + public void shouldLocateADifferentLeftToRightWordInATenLineGrid() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "fortranftw".toCharArray(), + "alxhpburyi".toCharArray(), + "clojurermt".toCharArray(), + "jalaycalmp".toCharArray() + }; + Set wordsToSearchFor = Set.of("fortran"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("fortran", Optional.of(new WordLocation(new Pair(1, 7), new Pair(7, 7)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'f', 'o', 'r', 't', 'r', 'a', 'n', 'f', 't', 'w'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'} - } - ); - + expectedLocations.put("fortran", Optional.of(new WordLocation( + new Pair(1, 7), + new Pair(7, 7) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate multiple words") - public void testShouldLocateMultipleWords() { + public void shouldLocateMultipleWords() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "fortranftw".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of("fortran", "clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("fortran", Optional.of(new WordLocation(new Pair(1, 7), new Pair(7, 7)))); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'f', 'o', 'r', 't', 'r', 'a', 'n', 'f', 't', 'w'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("fortran", Optional.of(new WordLocation( + new Pair(1, 7), + new Pair(7, 7) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate a single word written right to left") - public void testShouldLocateASingleWordRightToLeft() { + public void shouldLocateASingleWordWrittenRightToLeft() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"rixilelhrs".toCharArray()}; + Set wordsToSearchFor = Set.of("elixir"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 1), new Pair(1, 1)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'} - } - ); - + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 1), + new Pair(1, 1) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate multiple words written in different horizontal directions") - public void testShouldLocateMultipleWordsWrittenInDifferentHorizontalDirections() { + public void shouldLocateMultipleWordsWrittenInDifferentHorizontalDirections() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of("elixir", "clojure"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written top to bottom") - public void testLocatesWordsWrittenTopToBottom() { + public void shouldLocateWordsWrittenTopToBottom() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of("clojure", "elixir", "ecmascript"); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'} - } - ); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written bottom to top") - public void testLocatesWordsWrittenBottomToTop() { + public void shouldLocateWordsWrittenBottomToTop() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written top left to bottom right") - public void testLocatesWordsWrittenTopLeftToBottomRight() { + public void shouldLocateWordsWrittenTopLeftToBottomRight() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust", + "java" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - expectedLocations.put("java", Optional.of(new WordLocation(new Pair(1, 1), new Pair(4, 4)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + expectedLocations.put("java", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(4, 4) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written bottom right to top left") - public void testLocatesWordsWrittenBottomRightToTopLeft() { + public void shouldLocateWordsWrittenBottomRightToTopLeft() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust", + "java", + "lua" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - expectedLocations.put("java", Optional.of(new WordLocation(new Pair(1, 1), new Pair(4, 4)))); - expectedLocations.put("lua", Optional.of(new WordLocation(new Pair(8, 9), new Pair(6, 7)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + expectedLocations.put("java", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(4, 4) + ))); + expectedLocations.put("lua", Optional.of(new WordLocation( + new Pair(8, 9), + new Pair(6, 7) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written bottom left to top right") - public void testLocatesWordsWrittenBottomLeftToTopRight() { + public void shouldLocateWordsWrittenBottomLeftToTopRight() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust", + "java", + "lua", + "lisp" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - expectedLocations.put("java", Optional.of(new WordLocation(new Pair(1, 1), new Pair(4, 4)))); - expectedLocations.put("lua", Optional.of(new WordLocation(new Pair(8, 9), new Pair(6, 7)))); - expectedLocations.put("lisp", Optional.of(new WordLocation(new Pair(3, 6), new Pair(6, 3)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + expectedLocations.put("java", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(4, 4) + ))); + expectedLocations.put("lua", Optional.of(new WordLocation( + new Pair(8, 9), + new Pair(6, 7) + ))); + expectedLocations.put("lisp", Optional.of(new WordLocation( + new Pair(3, 6), + new Pair(6, 3) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should locate words written top right to bottom left") - public void testLocatesWordsWrittenTopRightToBottomLeft() { + public void shouldLocateWordsWrittenTopRightToBottomLeft() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust", + "java", + "lua", + "lisp", + "ruby" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - expectedLocations.put("java", Optional.of(new WordLocation(new Pair(1, 1), new Pair(4, 4)))); - expectedLocations.put("lua", Optional.of(new WordLocation(new Pair(8, 9), new Pair(6, 7)))); - expectedLocations.put("lisp", Optional.of(new WordLocation(new Pair(3, 6), new Pair(6, 3)))); - expectedLocations.put("ruby", Optional.of(new WordLocation(new Pair(8, 6), new Pair(5, 9)))); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + expectedLocations.put("java", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(4, 4) + ))); + expectedLocations.put("lua", Optional.of(new WordLocation( + new Pair(8, 9), + new Pair(6, 7) + ))); + expectedLocations.put("lisp", Optional.of(new WordLocation( + new Pair(3, 6), + new Pair(6, 3) + ))); + expectedLocations.put("ruby", Optional.of(new WordLocation( + new Pair(8, 6), + new Pair(5, 9) + ))); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should fail to locate a word that is not in the puzzle") - public void testFailsToLocateAWordsThatIsNotInThePuzzle() { + public void shouldFailToLocateAWordThatIsNotInThePuzzle() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "jefblpepre".toCharArray(), + "camdcimgtc".toCharArray(), + "oivokprjsm".toCharArray(), + "pbwasqroua".toCharArray(), + "rixilelhrs".toCharArray(), + "wolcqlirpc".toCharArray(), + "screeaumgr".toCharArray(), + "alxhpburyi".toCharArray(), + "jalaycalmp".toCharArray(), + "clojurermt".toCharArray() + }; + Set wordsToSearchFor = Set.of( + "clojure", + "elixir", + "ecmascript", + "rust", + "java", + "lua", + "lisp", + "ruby", + "haskell" + ); Map> expectedLocations = new HashMap<>(); - expectedLocations.put("clojure", Optional.of(new WordLocation(new Pair(1, 10), new Pair(7, 10)))); - expectedLocations.put("elixir", Optional.of(new WordLocation(new Pair(6, 5), new Pair(1, 5)))); - expectedLocations.put("ecmascript", Optional.of(new WordLocation(new Pair(10, 1), new Pair(10, 10)))); - expectedLocations.put("rust", Optional.of(new WordLocation(new Pair(9, 5), new Pair(9, 2)))); - expectedLocations.put("java", Optional.of(new WordLocation(new Pair(1, 1), new Pair(4, 4)))); - expectedLocations.put("lua", Optional.of(new WordLocation(new Pair(8, 9), new Pair(6, 7)))); - expectedLocations.put("lisp", Optional.of(new WordLocation(new Pair(3, 6), new Pair(6, 3)))); - expectedLocations.put("ruby", Optional.of(new WordLocation(new Pair(8, 6), new Pair(5, 9)))); - expectedLocations.put("haskell", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f', 'b', 'l', 'p', 'e', 'p', 'r', 'e'}, - {'c', 'a', 'm', 'd', 'c', 'i', 'm', 'g', 't', 'c'}, - {'o', 'i', 'v', 'o', 'k', 'p', 'r', 'j', 's', 'm'}, - {'p', 'b', 'w', 'a', 's', 'q', 'r', 'o', 'u', 'a'}, - {'r', 'i', 'x', 'i', 'l', 'e', 'l', 'h', 'r', 's'}, - {'w', 'o', 'l', 'c', 'q', 'l', 'i', 'r', 'p', 'c'}, - {'s', 'c', 'r', 'e', 'e', 'a', 'u', 'm', 'g', 'r'}, - {'a', 'l', 'x', 'h', 'p', 'b', 'u', 'r', 'y', 'i'}, - {'j', 'a', 'l', 'a', 'y', 'c', 'a', 'l', 'm', 'p'}, - {'c', 'l', 'o', 'j', 'u', 'r', 'e', 'r', 'm', 't'}}); - + expectedLocations.put("clojure", Optional.of(new WordLocation( + new Pair(1, 10), + new Pair(7, 10) + ))); + expectedLocations.put("elixir", Optional.of(new WordLocation( + new Pair(6, 5), + new Pair(1, 5) + ))); + expectedLocations.put("ecmascript", Optional.of(new WordLocation( + new Pair(10, 1), + new Pair(10, 10) + ))); + expectedLocations.put("rust", Optional.of(new WordLocation( + new Pair(9, 5), + new Pair(9, 2) + ))); + expectedLocations.put("java", Optional.of(new WordLocation( + new Pair(1, 1), + new Pair(4, 4) + ))); + expectedLocations.put("lua", Optional.of(new WordLocation( + new Pair(8, 9), + new Pair(6, 7) + ))); + expectedLocations.put("lisp", Optional.of(new WordLocation( + new Pair(3, 6), + new Pair(6, 3) + ))); + expectedLocations.put("ruby", Optional.of(new WordLocation( + new Pair(8, 6), + new Pair(5, 9) + ))); + expectedLocations.put("haskell", Optional.empty()); + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } - + @Disabled("Remove to run test") @Test @DisplayName("Should fail to locate words that are not on horizontal, vertical, or diagonal lines") - public void testFailToLocateWordsThatAreNotOnHorizontalVerticalOrDiagonalLines() { + public void shouldFailToLocateWordsThatAreNotOnHorizontalVerticalOrDiagonalLi() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"abc".toCharArray(), "def".toCharArray()}; + Set wordsToSearchFor = Set.of( + "aef", + "ced", + "abf", + "cbd" + ); Map> expectedLocations = new HashMap<>(); expectedLocations.put("aef", Optional.empty()); expectedLocations.put("ced", Optional.empty()); expectedLocations.put("abf", Optional.empty()); expectedLocations.put("cbd", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'j', 'e', 'f'}, - {'c', 'a', 'm'}}); - + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should not concatenate different lines to find a horizontal word") - public void testNotConcatenateDifferentLinesToFindAHorizontalWord() { + public void shouldNotConcatenateDifferentLinesToFindAHorizontalWord() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"abceli".toCharArray(), "xirdfg".toCharArray()}; + Set wordsToSearchFor = Set.of("elixir"); Map> expectedLocations = new HashMap<>(); expectedLocations.put("elixir", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'a', 'b', 'c', 'e', 'l', 'i'}, - {'x', 'i', 'r', 'd', 'f', 'g'}}); - + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } - + @Disabled("Remove to run test") @Test @DisplayName("Should not wrap around horizontally to find a word") - public void testNotWrapAroundHorizontallyToFindAWord() { + public void shouldNotWrapAroundHorizontallyToFindAWord() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{"silabcdefp".toCharArray()}; + Set wordsToSearchFor = Set.of("lisp"); Map> expectedLocations = new HashMap<>(); expectedLocations.put("lisp", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'s', 'i', 'l', 'a', 'b', 'c', 'd', 'e', 'f', 'p'} - } - ); - + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } @Disabled("Remove to run test") @Test @DisplayName("Should not wrap around vertically to find a word") - public void testNotWrapAroundVerticallyToFindAWord() { + public void shouldNotWrapAroundVerticallyToFindAWord() { + WordSearcher wordSearcher = new WordSearcher(); + char[][] grid = new char[][]{ + "s".toCharArray(), + "u".toCharArray(), + "r".toCharArray(), + "a".toCharArray(), + "b".toCharArray(), + "c".toCharArray(), + "t".toCharArray() + }; + Set wordsToSearchFor = Set.of("rust"); Map> expectedLocations = new HashMap<>(); expectedLocations.put("rust", Optional.empty()); - - Set searchWords = expectedLocations.keySet(); - - Map> actualLocations = wordSearcher.search( - searchWords, - new char[][]{ - {'s'}, - {'u'}, - {'r'}, - {'a'}, - {'b'}, - {'c'}, - {'t'}}); - + Map> actualLocations = wordSearcher.search(wordsToSearchFor, grid); assertThat(actualLocations).isEqualTo(expectedLocations); } diff --git a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java index 79c4a1d41..45f6eeb3e 100644 --- a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java +++ b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java @@ -7,208 +7,228 @@ public class WordProblemSolverTest { - WordProblemSolver solver = new WordProblemSolver(); + private WordProblemSolver solver = new WordProblemSolver(); @Test @DisplayName("just a number") - public void testJustANumber() { - assertThat(solver.solve("What is 5?")).isEqualTo(5); - } + public void justANumber() { - @Test - @DisplayName("just a zero") - public void testJustAZero() { - assertThat(solver.solve("What is 0?")).isEqualTo(0); - } + assertThat(solver.solve("What is 5?")).isEqualTo(5); - @Test - @DisplayName("just a negative number") - public void testJustANegativeNumber() { - assertThat(solver.solve("What is -123?")).isEqualTo(-123); } @Disabled("Remove to run test") @Test @DisplayName("addition") - public void testSingleAddition1() { - assertThat(solver.solve("What is 1 plus 1?")).isEqualTo(2); - } + public void addition() { - @Disabled("Remove to run test") - @Test - @DisplayName("addition with a left hand zero") - public void testAdditionWithALeftHandZero() { - assertThat(solver.solve("What is 0 plus 2?")).isEqualTo(2); - } + assertThat(solver.solve("What is 1 plus 1?")).isEqualTo(2); - @Disabled("Remove to run test") - @Test - @DisplayName("addition with a right hand zero") - public void testAdditionWithARightHandZero() { - assertThat(solver.solve("What is 3 plus 0?")).isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("more addition") - public void testSingleAddition2() { + public void moreAddition() { + assertThat(solver.solve("What is 53 plus 2?")).isEqualTo(55); + } @Disabled("Remove to run test") @Test @DisplayName("addition with negative numbers") - public void testSingleAdditionWithNegativeNumbers() { + public void additionWithNegativeNumbers() { + assertThat(solver.solve("What is -1 plus -10?")).isEqualTo(-11); + } @Disabled("Remove to run test") @Test @DisplayName("large addition") - public void testSingleAdditionOfLargeNumbers() { + public void largeAddition() { + assertThat(solver.solve("What is 123 plus 45678?")).isEqualTo(45801); + } @Disabled("Remove to run test") @Test @DisplayName("subtraction") - public void testSingleSubtraction() { + public void subtraction() { + assertThat(solver.solve("What is 4 minus -12?")).isEqualTo(16); + } @Disabled("Remove to run test") @Test @DisplayName("multiplication") - public void testSingleMultiplication() { + public void multiplication() { + assertThat(solver.solve("What is -3 multiplied by 25?")).isEqualTo(-75); + } @Disabled("Remove to run test") @Test @DisplayName("division") - public void testSingleDivision() { + public void division() { + assertThat(solver.solve("What is 33 divided by -3?")).isEqualTo(-11); + } @Disabled("Remove to run test") @Test @DisplayName("multiple additions") - public void testMultipleAdditions() { + public void multipleAdditions() { + assertThat(solver.solve("What is 1 plus 1 plus 1?")).isEqualTo(3); + } @Disabled("Remove to run test") @Test @DisplayName("addition and subtraction") - public void testAdditionThenSubtraction() { + public void additionAndSubtraction() { + assertThat(solver.solve("What is 1 plus 5 minus -2?")).isEqualTo(8); + } @Disabled("Remove to run test") @Test @DisplayName("multiple subtraction") - public void testMultipleSubtractions() { + public void multipleSubtraction() { + assertThat(solver.solve("What is 20 minus 4 minus 13?")).isEqualTo(3); + } @Disabled("Remove to run test") @Test @DisplayName("subtraction then addition") - public void testSubtractionThenAddition() { + public void subtractionThenAddition() { + assertThat(solver.solve("What is 17 minus 6 plus 3?")).isEqualTo(14); + } @Disabled("Remove to run test") @Test @DisplayName("multiple multiplication") - public void testMultipleMultiplications() { + public void multipleMultiplication() { + assertThat(solver.solve("What is 2 multiplied by -2 multiplied by 3?")).isEqualTo(-12); + } @Disabled("Remove to run test") @Test @DisplayName("addition and multiplication") - public void testAdditionThenMultiplication() { + public void additionAndMultiplication() { + assertThat(solver.solve("What is -3 plus 7 multiplied by -2?")).isEqualTo(-8); + } @Disabled("Remove to run test") @Test @DisplayName("multiple division") - public void testMultipleDivisions() { + public void multipleDivision() { + assertThat(solver.solve("What is -12 divided by 2 divided by -3?")).isEqualTo(2); + } @Disabled("Remove to run test") @Test @DisplayName("unknown operation") - public void testUnknownOperation() { + public void unknownOperation() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 52 cubed?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("Non math question") - public void testNonMathQuestion() { - // See https://en.wikipedia.org/wiki/President_of_the_United_States if you really need to know! + public void nonMathQuestion() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("Who is the President of the United States?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("reject problem missing an operand") - public void testMissingAnOperand() { + public void rejectProblemMissingAnOperand() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test - @DisplayName("reject problem with no operands or operator") - public void testNoOperandsOrOperators() { + @DisplayName("reject problem with no operands or operators") + public void rejectProblemWithNoOperandsOrOperators() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("reject two operations in a row") - public void testTwoOperationsInARow() { + public void rejectTwoOperationsInARow() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus plus 2?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("reject two numbers in a row") - public void testTwoNumbersAfterOperation() { + public void rejectTwoNumbersInARow() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus 2 1?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("reject postfix notation") - public void testPostfixNotation() { + public void rejectPostfixNotation() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 2 plus?")) .withMessage("I'm sorry, I don't understand the question!"); + } @Disabled("Remove to run test") @Test @DisplayName("reject prefix notation") - public void testPrefixNotation() { + public void rejectPrefixNotation() { + assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is plus 1 2?")) .withMessage("I'm sorry, I don't understand the question!"); + } + } diff --git a/exercises/practice/yacht/src/test/java/YachtTest.java b/exercises/practice/yacht/src/test/java/YachtTest.java index 2a5e873e6..9f5db7bec 100644 --- a/exercises/practice/yacht/src/test/java/YachtTest.java +++ b/exercises/practice/yacht/src/test/java/YachtTest.java @@ -9,232 +9,261 @@ public class YachtTest { @Test @DisplayName("Yacht") public void yacht() { - Yacht yacht = new Yacht(new int[]{ 5, 5, 5, 5, 5 }, YachtCategory.YACHT); - assertThat(yacht.score()).isEqualTo(50); + assertThat(new Yacht(new int[]{5, 5, 5, 5, 5}, YachtCategory.YACHT) + .score()) + .isEqualTo(50); } @Disabled("Remove to run test") @Test @DisplayName("Not Yacht") public void notYacht() { - Yacht yacht = new Yacht(new int[]{ 1, 3, 3, 2, 5 }, YachtCategory.YACHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 3, 3, 2, 5}, YachtCategory.YACHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Ones") public void ones() { - Yacht yacht = new Yacht(new int[]{ 1, 1, 1, 3, 5 }, YachtCategory.ONES); - assertThat(yacht.score()).isEqualTo(3); + assertThat(new Yacht(new int[]{1, 1, 1, 3, 5}, YachtCategory.ONES) + .score()) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("Ones, out of order") public void onesOutOfOrder() { - Yacht yacht = new Yacht(new int[]{ 3, 1, 1, 5, 1 }, YachtCategory.ONES); - assertThat(yacht.score()).isEqualTo(3); + assertThat(new Yacht(new int[]{3, 1, 1, 5, 1}, YachtCategory.ONES) + .score()) + .isEqualTo(3); } @Disabled("Remove to run test") @Test @DisplayName("No ones") public void noOnes() { - Yacht yacht = new Yacht(new int[]{ 4, 3, 6, 5, 5 }, YachtCategory.ONES); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{4, 3, 6, 5, 5}, YachtCategory.ONES) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Twos") public void twos() { - Yacht yacht = new Yacht(new int[]{ 2, 3, 4, 5, 6 }, YachtCategory.TWOS); - assertThat(yacht.score()).isEqualTo(2); + assertThat(new Yacht(new int[]{2, 3, 4, 5, 6}, YachtCategory.TWOS) + .score()) + .isEqualTo(2); } @Disabled("Remove to run test") @Test @DisplayName("Fours") public void fours() { - Yacht yacht = new Yacht(new int[]{ 1, 4, 1, 4, 1 }, YachtCategory.FOURS); - assertThat(yacht.score()).isEqualTo(8); + assertThat(new Yacht(new int[]{1, 4, 1, 4, 1}, YachtCategory.FOURS) + .score()) + .isEqualTo(8); } @Disabled("Remove to run test") @Test @DisplayName("Yacht counted as threes") public void yachtCountedAsThrees() { - Yacht yacht = new Yacht(new int[]{ 3, 3, 3, 3, 3 }, YachtCategory.THREES); - assertThat(yacht.score()).isEqualTo(15); + assertThat(new Yacht(new int[]{3, 3, 3, 3, 3}, YachtCategory.THREES) + .score()) + .isEqualTo(15); } @Disabled("Remove to run test") @Test @DisplayName("Yacht of 3s counted as fives") - public void yachtOfThreesCountedAsFives() { - Yacht yacht = new Yacht(new int[]{ 3, 3, 3, 3, 3 }, YachtCategory.FIVES); - assertThat(yacht.score()).isEqualTo(0); + public void yachtOf3sCountedAsFives() { + assertThat(new Yacht(new int[]{3, 3, 3, 3, 3}, YachtCategory.FIVES) + .score()) + .isEqualTo(0); } - + @Disabled("Remove to run test") @Test @DisplayName("Fives") public void fives() { - Yacht yacht = new Yacht(new int[]{ 1, 5, 3, 5, 3 }, YachtCategory.FIVES); - assertThat(yacht.score()).isEqualTo(10); + assertThat(new Yacht(new int[]{1, 5, 3, 5, 3}, YachtCategory.FIVES) + .score()) + .isEqualTo(10); } @Disabled("Remove to run test") @Test @DisplayName("Sixes") public void sixes() { - Yacht yacht = new Yacht(new int[]{ 2, 3, 4, 5, 6 }, YachtCategory.SIXES); - assertThat(yacht.score()).isEqualTo(6); + assertThat(new Yacht(new int[]{2, 3, 4, 5, 6}, YachtCategory.SIXES) + .score()) + .isEqualTo(6); } @Disabled("Remove to run test") @Test @DisplayName("Full house two small, three big") public void fullHouseTwoSmallThreeBig() { - Yacht yacht = new Yacht(new int[]{ 2, 2, 4, 4, 4 }, YachtCategory.FULL_HOUSE); - assertThat(yacht.score()).isEqualTo(16); + assertThat(new Yacht(new int[]{2, 2, 4, 4, 4}, YachtCategory.FULL_HOUSE) + .score()) + .isEqualTo(16); } @Disabled("Remove to run test") @Test @DisplayName("Full house three small, two big") public void fullHouseThreeSmallTwoBig() { - Yacht yacht = new Yacht(new int[]{ 5, 3, 3, 5, 3 }, YachtCategory.FULL_HOUSE); - assertThat(yacht.score()).isEqualTo(19); + assertThat(new Yacht(new int[]{5, 3, 3, 5, 3}, YachtCategory.FULL_HOUSE) + .score()) + .isEqualTo(19); } @Disabled("Remove to run test") @Test @DisplayName("Two pair is not a full house") public void twoPairIsNotAFullHouse() { - Yacht yacht = new Yacht(new int[]{ 2, 2, 4, 4, 5 }, YachtCategory.FULL_HOUSE); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{2, 2, 4, 4, 5}, YachtCategory.FULL_HOUSE) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Four of a kind is not a full house") public void fourOfAKindIsNotAFullHouse() { - Yacht yacht = new Yacht(new int[]{ 1, 4, 4, 4, 4 }, YachtCategory.FULL_HOUSE); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 4, 4, 4, 4}, YachtCategory.FULL_HOUSE) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Yacht is not a full house") public void yachtIsNotAFullHouse() { - Yacht yacht = new Yacht(new int[]{ 2, 2, 2, 2, 2 }, YachtCategory.FULL_HOUSE); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{2, 2, 2, 2, 2}, YachtCategory.FULL_HOUSE) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Four of a Kind") public void fourOfAKind() { - Yacht yacht = new Yacht(new int[]{ 6, 6, 4, 6, 6 }, YachtCategory.FOUR_OF_A_KIND); - assertThat(yacht.score()).isEqualTo(24); + assertThat(new Yacht(new int[]{6, 6, 4, 6, 6}, YachtCategory.FOUR_OF_A_KIND) + .score()) + .isEqualTo(24); } @Disabled("Remove to run test") @Test @DisplayName("Yacht can be scored as Four of a Kind") public void yachtCanBeScoredAsFourOfAKind() { - Yacht yacht = new Yacht(new int[]{ 3, 3, 3, 3, 3 }, YachtCategory.FOUR_OF_A_KIND); - assertThat(yacht.score()).isEqualTo(12); + assertThat(new Yacht(new int[]{3, 3, 3, 3, 3}, YachtCategory.FOUR_OF_A_KIND) + .score()) + .isEqualTo(12); } @Disabled("Remove to run test") @Test @DisplayName("Full house is not Four of a Kind") public void fullHouseIsNotFourOfAKind() { - Yacht yacht = new Yacht(new int[]{ 3, 3, 3, 5, 5 }, YachtCategory.FOUR_OF_A_KIND); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{3, 3, 3, 5, 5}, YachtCategory.FOUR_OF_A_KIND) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Little Straight") public void littleStraight() { - Yacht yacht = new Yacht(new int[]{ 3, 5, 4, 1, 2 }, YachtCategory.LITTLE_STRAIGHT); - assertThat(yacht.score()).isEqualTo(30); + assertThat(new Yacht(new int[]{3, 5, 4, 1, 2}, YachtCategory.LITTLE_STRAIGHT) + .score()) + .isEqualTo(30); } @Disabled("Remove to run test") @Test @DisplayName("Little Straight as Big Straight") public void littleStraightAsBigStraight() { - Yacht yacht = new Yacht(new int[]{ 1, 2, 3, 4, 5 }, YachtCategory.BIG_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 2, 3, 4, 5}, YachtCategory.BIG_STRAIGHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Four in order but not a little straight") public void fourInOrderButNotALittleStraight() { - Yacht yacht = new Yacht(new int[]{ 1, 1, 2, 3, 4 }, YachtCategory.LITTLE_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 1, 2, 3, 4}, YachtCategory.LITTLE_STRAIGHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("No pairs but not a little straight") public void noPairsButNotALittleStraight() { - Yacht yacht = new Yacht(new int[]{ 1, 2, 3, 4, 6 }, YachtCategory.LITTLE_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 2, 3, 4, 6}, YachtCategory.LITTLE_STRAIGHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Minimum is 1, maximum is 5, but not a little straight") public void minimumIs1MaximumIs5ButNotALittleStraight() { - Yacht yacht = new Yacht(new int[]{ 1, 1, 3, 4, 5 }, YachtCategory.LITTLE_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{1, 1, 3, 4, 5}, YachtCategory.LITTLE_STRAIGHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Big Straight") public void bigStraight() { - Yacht yacht = new Yacht(new int[]{ 4, 6, 2, 5, 3 }, YachtCategory.BIG_STRAIGHT); - assertThat(yacht.score()).isEqualTo(30); + assertThat(new Yacht(new int[]{4, 6, 2, 5, 3}, YachtCategory.BIG_STRAIGHT) + .score()) + .isEqualTo(30); } @Disabled("Remove to run test") @Test @DisplayName("Big Straight as little straight") public void bigStraightAsLittleStraight() { - Yacht yacht = new Yacht(new int[]{ 6, 5, 4, 3, 2 }, YachtCategory.LITTLE_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{6, 5, 4, 3, 2}, YachtCategory.LITTLE_STRAIGHT) + .score()) + .isEqualTo(0); } - + @Disabled("Remove to run test") @Test @DisplayName("No pairs but not a big straight") public void noPairsButNotABigStraight() { - Yacht yacht = new Yacht(new int[]{ 6, 5, 4, 3, 1 }, YachtCategory.BIG_STRAIGHT); - assertThat(yacht.score()).isEqualTo(0); + assertThat(new Yacht(new int[]{6, 5, 4, 3, 1}, YachtCategory.BIG_STRAIGHT) + .score()) + .isEqualTo(0); } @Disabled("Remove to run test") @Test @DisplayName("Choice") public void choice() { - Yacht yacht = new Yacht(new int[]{ 3, 3, 5, 6, 6 }, YachtCategory.CHOICE); - assertThat(yacht.score()).isEqualTo(23); + assertThat(new Yacht(new int[]{3, 3, 5, 6, 6}, YachtCategory.CHOICE) + .score()) + .isEqualTo(23); } @Disabled("Remove to run test") @Test @DisplayName("Yacht as choice") public void yachtAsChoice() { - Yacht yacht = new Yacht(new int[]{ 2, 2, 2, 2, 2 }, YachtCategory.CHOICE); - assertThat(yacht.score()).isEqualTo(10); + assertThat(new Yacht(new int[]{2, 2, 2, 2, 2}, YachtCategory.CHOICE) + .score()) + .isEqualTo(10); } } diff --git a/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java b/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java index b0bb118fe..614d8ec28 100644 --- a/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java +++ b/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java @@ -10,7 +10,9 @@ public class ZebraPuzzleTest { @DisplayName("resident who drinks water") public void residentWhoDrinksWater() { ZebraPuzzle zebraPuzzle = new ZebraPuzzle(); + assertThat(zebraPuzzle.getWaterDrinker()).isEqualTo("Norwegian"); + } @Disabled("Remove to run test") @@ -18,7 +20,9 @@ public void residentWhoDrinksWater() { @DisplayName("resident who owns zebra") public void residentWhoOwnsZebra() { ZebraPuzzle zebraPuzzle = new ZebraPuzzle(); + assertThat(zebraPuzzle.getZebraOwner()).isEqualTo("Japanese"); + } } diff --git a/exercises/practice/zipper/src/test/java/ZipperTest.java b/exercises/practice/zipper/src/test/java/ZipperTest.java index d8797814f..6dbcbb393 100644 --- a/exercises/practice/zipper/src/test/java/ZipperTest.java +++ b/exercises/practice/zipper/src/test/java/ZipperTest.java @@ -23,14 +23,14 @@ public void setup() { @Test @DisplayName("data is retained") - public void testToTree() { + public void dataIsRetained() { assertThat(zipper.toTree()).isEqualTo(binaryTree); } @Disabled("Remove to run test") @Test @DisplayName("left, right and value") - public void testLeftRightAndValue() { + public void leftRightAndValue() { zipper = binaryTree.getRoot(); assertThat(zipper.left.right.getValue()).isEqualTo(3); } @@ -38,7 +38,7 @@ public void testLeftRightAndValue() { @Disabled("Remove to run test") @Test @DisplayName("dead end") - public void testDeadEnd() { + public void deadEnd() { zipper = binaryTree.getRoot(); assertThat(zipper.left.left).isNull(); } @@ -46,7 +46,7 @@ public void testDeadEnd() { @Disabled("Remove to run test") @Test @DisplayName("tree from deep focus") - public void testToTreeFromDeepFocus() { + public void treeFromDeepFocus() { zipper = binaryTree.getRoot(); assertThat(zipper.left.right.toTree()).isEqualTo(binaryTree); } @@ -54,7 +54,7 @@ public void testToTreeFromDeepFocus() { @Disabled("Remove to run test") @Test @DisplayName("traversing up from top") - public void testTraversingUpFromTop() { + public void traversingUpFromTop() { zipper = binaryTree.getRoot(); assertThat(zipper.up).isNull(); } @@ -62,7 +62,7 @@ public void testTraversingUpFromTop() { @Disabled("Remove to run test") @Test @DisplayName("left, right, and up") - public void testLeftRightAndUp() { + public void leftRightAndUp() { zipper = binaryTree.getRoot(); assertThat(zipper.left.up.right.up.left.right.getValue()).isEqualTo(3); } @@ -70,7 +70,7 @@ public void testLeftRightAndUp() { @Disabled("Remove to run test") @Test @DisplayName("test ability to descend multiple levels and return") - public void testAbilityToReturnAfterMultipleLevelDescend() { + public void testAbilityToDescendMultipleLevelsAndReturn() { zipper = binaryTree.getRoot(); assertThat(zipper.left.right.up.up.getValue()).isEqualTo(1); } @@ -78,93 +78,87 @@ public void testAbilityToReturnAfterMultipleLevelDescend() { @Disabled("Remove to run test") @Test @DisplayName("set_value") - public void testSetValue() { + public void setValue() { zipper = binaryTree.getRoot(); zipper = zipper.left; zipper.setValue(5); String expected = "value: 1, " + - "left: { " + - "value: 5, " + - "left: null, " + - "right: { " + - "value: 3, " + - "left: null, " + - "right: null } }, " + - "right: { " + - "value: 4, " + - "left: null, " + - "right: null }"; + "left: { value: 5, " + + "left: null, " + + "right: { value: 3, " + + "left: null, " + + "right: null } }, " + + "right: { value: 4, " + + "left: null, " + + "right: null }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("set_value after traversing up") - public void testSetValueAfterTraversingUp() { + public void setValueAfterTraversingUp() { zipper = binaryTree.getRoot(); zipper = zipper.left.right.up; zipper.setValue(5); String expected = "value: 1, " + - "left: { " + - "value: 5, " + - "left: null, " + - "right: { " + - "value: 3, " + - "left: null, " + - "right: null } }, " + - "right: { " + - "value: 4, " + - "left: null, " + - "right: null }"; + "left: { value: 5, " + + "left: null, " + + "right: { value: 3, " + + "left: null, " + + "right: null } }, " + + "right: { value: 4, " + + "left: null, " + + "right: null }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("set_left with leaf") - public void testSetLeftWithLeaf() { + public void setLeftWithLeaf() { zipper = binaryTree.getRoot(); zipper = zipper.left; zipper.setLeft(new Zipper(5)); String expected = "value: 1, " + - "left: { " + - "value: 2, " + - "left: { " + - "value: 5, " + - "left: null, " + - "right: null }, " + - "right: { " + - "value: 3, " + - "left: null, " + - "right: null } }, " + - "right: { " + - "value: 4, " + - "left: null, " + - "right: null }"; + "left: { value: 2, " + + "left: { value: 5, " + + "left: null, " + + "right: null }, " + + "right: { value: 3, " + + "left: null, " + + "right: null } }, " + + "right: { value: 4, " + + "left: null, " + + "right: null }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("set_right with null") - public void testSetRightWithNull() { + public void setRightWithNull() { zipper = binaryTree.getRoot(); zipper = zipper.left; zipper.setRight(null); String expected = "value: 1, " + - "left: { value: 2, left: null, right: null }, " + - "right: { value: 4, left: null, right: null }"; + "left: { value: 2, " + + "left: null, " + + "right: null }, " + + "right: { value: 4, " + + "left: null, " + + "right: null }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("set_right with subtree") - public void testSetRightWithSubtree() { + public void setRightWithSubtree() { BinaryTree subtree = new BinaryTree(6); subtree.getRoot().setLeft(new Zipper(7)); subtree.getRoot().setRight(new Zipper(8)); @@ -172,55 +166,48 @@ public void testSetRightWithSubtree() { zipper.setRight(subtree.getRoot()); String expected = "value: 1, " + - "left: { " + - "value: 2, " + - "left: null, " + - "right: { " + - "value: 3, " + - "left: null, " + - "right: null } }, " + - "right: { " + - "value: 6, " + - "left: { " + - "value: 7, " + - "left: null, " + - "right: null }, " + - "right: { " + - "value: 8, " + - "left: null, " + - "right: null } }"; + "left: { value: 2, " + + "left: null, " + + "right: { value: 3, " + + "left: null, " + + "right: null } }, " + + "right: { value: 6, " + + "left: { value: 7, " + + "left: null, " + + "right: null }, " + + "right: { value: 8, " + + "left: null, " + + "right: null } }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("set_value on deep focus") - public void testSetValueOnDeepFocus() { + public void setValueOnDeepFocus() { zipper = binaryTree.getRoot(); zipper = zipper.left.right; zipper.setValue(5); String expected = "value: 1, " + - "left: { " + - "value: 2, " + - "left: null, " + - "right: { " + - "value: 5, " + - "left: null, " + - "right: null } }, " + - "right: { " + - "value: 4, " + - "left: null, " + - "right: null }"; + "left: { value: 2, " + + "left: null, " + + "right: { value: 5, " + + "left: null, " + + "right: null } }, " + + "right: { value: 4, " + + "left: null, " + + "right: null }"; assertThat(zipper.toTree().printTree()).isEqualTo(expected); } @Disabled("Remove to run test") @Test @DisplayName("different paths to same zipper") - public void differentPathToSameZipper() { + public void differentPathsToSameZipper() { Zipper zipper1 = binaryTree.getRoot().left.up.right; Zipper zipper2 = binaryTree.getRoot().right; assertThat(zipper1).isEqualTo(zipper2); } + } From 28353cceb0105c3bb2445502069a1ccb14d8e292 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 4 Dec 2026 00:41:11 +0530 Subject: [PATCH 2/3] Use beforeeach across 23 exercises --- .../practice/affine-cipher/.meta/template.hbs | 8 +++- .../src/test/java/AffineCipherTest.java | 8 +++- .../baffling-birthdays/.meta/template.hbs | 8 +++- .../src/test/java/BafflingBirthdaysTest.java | 8 +++- .../practice/bottle-song/.meta/template.hbs | 8 +++- .../src/test/java/BottleSongTest.java | 8 +++- .../src/test/java/CircularBufferTest.java | 40 ------------------- exercises/practice/diamond/.meta/template.hbs | 8 +++- .../src/test/java/DiamondPrinterTest.java | 8 +++- .../practice/dnd-character/.meta/template.hbs | 8 +++- .../src/test/java/DnDCharacterTest.java | 8 +++- exercises/practice/etl/.meta/template.hbs | 8 +++- .../practice/etl/src/test/java/EtlTest.java | 8 +++- .../practice/food-chain/.meta/template.hbs | 8 +++- .../src/test/java/FoodChainTest.java | 8 +++- exercises/practice/forth/.meta/template.hbs | 8 +++- .../src/test/java/ForthEvaluatorTest.java | 8 +++- exercises/practice/grains/.meta/template.hbs | 8 +++- .../grains/src/test/java/GrainsTest.java | 8 +++- exercises/practice/house/.meta/template.hbs | 8 +++- .../house/src/test/java/HouseTest.java | 8 +++- .../killer-sudoku-helper/.meta/template.hbs | 8 +++- .../src/test/java/KillerSudokuHelperTest.java | 8 +++- .../practice/knapsack/.meta/template.hbs | 8 +++- .../knapsack/src/test/java/KnapsackTest.java | 8 +++- exercises/practice/ledger/.meta/template.hbs | 8 +++- .../ledger/src/test/java/LedgerTest.java | 8 +++- .../palindrome-products/.meta/template.hbs | 8 +++- .../test/java/PalindromeCalculatorTest.java | 8 +++- .../pascals-triangle/.meta/template.hbs | 8 +++- .../java/PascalsTriangleGeneratorTest.java | 8 +++- .../protein-translation/.meta/template.hbs | 8 +++- .../src/test/java/ProteinTranslatorTest.java | 8 +++- .../run-length-encoding/.meta/template.hbs | 8 +++- .../src/test/java/RunLengthEncodingTest.java | 8 +++- .../practice/satellite/.meta/template.hbs | 8 +++- .../src/test/java/SatelliteTest.java | 8 +++- .../practice/simple-cipher/.meta/template.hbs | 3 +- .../src/test/java/SimpleCipherTest.java | 3 +- .../state-of-tic-tac-toe/.meta/template.hbs | 8 +++- .../src/test/java/StateOfTicTacToeTest.java | 8 +++- .../practice/twelve-days/.meta/template.hbs | 8 +++- .../src/test/java/TwelveDaysTest.java | 8 +++- .../.meta/template.hbs | 8 +++- .../test/java/VariableLengthQuantityTest.java | 8 +++- exercises/practice/wordy/.meta/template.hbs | 8 +++- .../src/test/java/WordProblemSolverTest.java | 8 +++- .../service/TemplateRenderer.java | 10 ++++- 48 files changed, 320 insertions(+), 88 deletions(-) diff --git a/exercises/practice/affine-cipher/.meta/template.hbs b/exercises/practice/affine-cipher/.meta/template.hbs index 3ceb2e961..71d2a9e83 100644 --- a/exercises/practice/affine-cipher/.meta/template.hbs +++ b/exercises/practice/affine-cipher/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class AffineCipherTest { - private AffineCipher affineCipher = new AffineCipher(); + private AffineCipher affineCipher; + + @BeforeEach + public void setUp() { + affineCipher = new AffineCipher(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java index 2ed6022b6..1aab8f84a 100644 --- a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java +++ b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ public class AffineCipherTest { - private AffineCipher affineCipher = new AffineCipher(); + private AffineCipher affineCipher; + + @BeforeEach + public void setUp() { + affineCipher = new AffineCipher(); + } @Test @DisplayName("encode -> encode yes") diff --git a/exercises/practice/baffling-birthdays/.meta/template.hbs b/exercises/practice/baffling-birthdays/.meta/template.hbs index e2f511b35..7cd573831 100644 --- a/exercises/practice/baffling-birthdays/.meta/template.hbs +++ b/exercises/practice/baffling-birthdays/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,7 +11,12 @@ import static org.assertj.core.api.Assertions.offset; public class BafflingBirthdaysTest { - private BafflingBirthdays birthdays = new BafflingBirthdays(); + private BafflingBirthdays birthdays; + + @BeforeEach + public void setUp() { + birthdays = new BafflingBirthdays(); + } {{#each testCases}} {{#if disabled~}} diff --git a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java index 70303f36d..b77c11f7e 100644 --- a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java +++ b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,7 +11,12 @@ public class BafflingBirthdaysTest { - private BafflingBirthdays birthdays = new BafflingBirthdays(); + private BafflingBirthdays birthdays; + + @BeforeEach + public void setUp() { + birthdays = new BafflingBirthdays(); + } @Test @DisplayName("shared birthday -> one birthdate") diff --git a/exercises/practice/bottle-song/.meta/template.hbs b/exercises/practice/bottle-song/.meta/template.hbs index 0ca63ef99..02490f904 100644 --- a/exercises/practice/bottle-song/.meta/template.hbs +++ b/exercises/practice/bottle-song/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class BottleSongTest { - private BottleSong bottleSong = new BottleSong(); + private BottleSong bottleSong; + + @BeforeEach + public void setUp() { + bottleSong = new BottleSong(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/bottle-song/src/test/java/BottleSongTest.java b/exercises/practice/bottle-song/src/test/java/BottleSongTest.java index 28ec60aca..c2588aa36 100644 --- a/exercises/practice/bottle-song/src/test/java/BottleSongTest.java +++ b/exercises/practice/bottle-song/src/test/java/BottleSongTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class BottleSongTest { - private BottleSong bottleSong = new BottleSong(); + private BottleSong bottleSong; + + @BeforeEach + public void setUp() { + bottleSong = new BottleSong(); + } @Test @DisplayName("verse -> single verse -> first generic verse") diff --git a/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java b/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java index fc818c0b4..071ab715f 100644 --- a/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java +++ b/exercises/practice/circular-buffer/src/test/java/CircularBufferTest.java @@ -24,7 +24,6 @@ public void canReadAnItemJustWritten() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); - assertThat(buffer.read()).isEqualTo(1); } @@ -35,7 +34,6 @@ public void eachItemMayOnlyBeReadOnce() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); - assertThat(buffer.read()).isEqualTo(1); assertThatExceptionOfType(BufferIOException.class) @@ -50,11 +48,8 @@ public void itemsAreReadInTheOrderTheyAreWritten() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); - buffer.write(2); - assertThat(buffer.read()).isEqualTo(1); - assertThat(buffer.read()).isEqualTo(2); } @@ -78,11 +73,8 @@ public void aReadFreesUpCapacityForAnotherWrite() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); - assertThat(buffer.read()).isEqualTo(1); - buffer.write(2); - assertThat(buffer.read()).isEqualTo(2); } @@ -93,15 +85,10 @@ public void readPositionIsMaintainedEvenAcrossMultipleWrites() throws BufferIOEx CircularBuffer buffer = new CircularBuffer<>(3); buffer.write(1); - buffer.write(2); - assertThat(buffer.read()).isEqualTo(1); - buffer.write(3); - assertThat(buffer.read()).isEqualTo(2); - assertThat(buffer.read()).isEqualTo(3); } @@ -112,7 +99,6 @@ public void itemsClearedOutOfBufferCanTBeRead() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); - buffer.clear(); assertThatExceptionOfType(BufferIOException.class) @@ -127,11 +113,8 @@ public void clearFreesUpCapacityForAnotherWrite() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.write(1); - buffer.clear(); - buffer.write(2); - assertThat(buffer.read()).isEqualTo(2); } @@ -142,9 +125,7 @@ public void clearDoesNothingOnEmptyBuffer() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(1); buffer.clear(); - buffer.write(1); - assertThat(buffer.read()).isEqualTo(1); } @@ -155,11 +136,8 @@ public void overwriteActsLikeWriteOnNonFullBuffer() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); - buffer.overwrite(2); - assertThat(buffer.read()).isEqualTo(1); - assertThat(buffer.read()).isEqualTo(2); } @@ -170,13 +148,9 @@ public void overwriteReplacesTheOldestItemOnFullBuffer() throws BufferIOExceptio CircularBuffer buffer = new CircularBuffer<>(2); buffer.write(1); - buffer.write(2); - buffer.overwrite(3); - assertThat(buffer.read()).isEqualTo(2); - assertThat(buffer.read()).isEqualTo(3); } @@ -187,21 +161,13 @@ public void overwriteReplacesTheOldestItemRemainingInBufferFollowingARead() thro CircularBuffer buffer = new CircularBuffer<>(3); buffer.write(1); - buffer.write(2); - buffer.write(3); - assertThat(buffer.read()).isEqualTo(1); - buffer.write(4); - buffer.overwrite(5); - assertThat(buffer.read()).isEqualTo(3); - assertThat(buffer.read()).isEqualTo(4); - assertThat(buffer.read()).isEqualTo(5); } @@ -212,17 +178,11 @@ public void initialClearDoesNotAffectWrappingAround() throws BufferIOException { CircularBuffer buffer = new CircularBuffer<>(2); buffer.clear(); - buffer.write(1); - buffer.write(2); - buffer.overwrite(3); - buffer.overwrite(4); - assertThat(buffer.read()).isEqualTo(3); - assertThat(buffer.read()).isEqualTo(4); assertThatExceptionOfType(BufferIOException.class) diff --git a/exercises/practice/diamond/.meta/template.hbs b/exercises/practice/diamond/.meta/template.hbs index d08bc4cc9..66d63b706 100644 --- a/exercises/practice/diamond/.meta/template.hbs +++ b/exercises/practice/diamond/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class DiamondPrinterTest { - private DiamondPrinter diamondPrinter = new DiamondPrinter(); + private DiamondPrinter diamondPrinter; + + @BeforeEach + public void setUp() { + diamondPrinter = new DiamondPrinter(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java b/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java index c8c76f71d..d2ab24610 100644 --- a/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java +++ b/exercises/practice/diamond/src/test/java/DiamondPrinterTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class DiamondPrinterTest { - private DiamondPrinter diamondPrinter = new DiamondPrinter(); + private DiamondPrinter diamondPrinter; + + @BeforeEach + public void setUp() { + diamondPrinter = new DiamondPrinter(); + } @Test @DisplayName("Degenerate case with a single 'A' row") diff --git a/exercises/practice/dnd-character/.meta/template.hbs b/exercises/practice/dnd-character/.meta/template.hbs index 56a0d3edb..6461dd1a9 100644 --- a/exercises/practice/dnd-character/.meta/template.hbs +++ b/exercises/practice/dnd-character/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class DnDCharacterTest { - private DnDCharacter dndCharacter = new DnDCharacter(); + private DnDCharacter dndCharacter; + + @BeforeEach + public void setUp() { + dndCharacter = new DnDCharacter(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java index 4803529ab..36ae316f8 100644 --- a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java +++ b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class DnDCharacterTest { - private DnDCharacter dndCharacter = new DnDCharacter(); + private DnDCharacter dndCharacter; + + @BeforeEach + public void setUp() { + dndCharacter = new DnDCharacter(); + } @Test @DisplayName("ability modifier -> ability modifier for score 3 is -4") diff --git a/exercises/practice/etl/.meta/template.hbs b/exercises/practice/etl/.meta/template.hbs index cbee2f031..9c1e3ae2e 100644 --- a/exercises/practice/etl/.meta/template.hbs +++ b/exercises/practice/etl/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class EtlTest { - private final Etl etl = new Etl(); + private Etl etl; + + @BeforeEach + public void setUp() { + etl = new Etl(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/etl/src/test/java/EtlTest.java b/exercises/practice/etl/src/test/java/EtlTest.java index 250323ab5..b51c0e1fd 100644 --- a/exercises/practice/etl/src/test/java/EtlTest.java +++ b/exercises/practice/etl/src/test/java/EtlTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class EtlTest { - private final Etl etl = new Etl(); + private Etl etl; + + @BeforeEach + public void setUp() { + etl = new Etl(); + } @Test @DisplayName("single letter") diff --git a/exercises/practice/food-chain/.meta/template.hbs b/exercises/practice/food-chain/.meta/template.hbs index f52bde7cd..0a8d17e71 100644 --- a/exercises/practice/food-chain/.meta/template.hbs +++ b/exercises/practice/food-chain/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class FoodChainTest { - private FoodChain foodChain = new FoodChain(); + private FoodChain foodChain; + + @BeforeEach + public void setUp() { + foodChain = new FoodChain(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/food-chain/src/test/java/FoodChainTest.java b/exercises/practice/food-chain/src/test/java/FoodChainTest.java index d86c6de2b..8747ee595 100644 --- a/exercises/practice/food-chain/src/test/java/FoodChainTest.java +++ b/exercises/practice/food-chain/src/test/java/FoodChainTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class FoodChainTest { - private FoodChain foodChain = new FoodChain(); + private FoodChain foodChain; + + @BeforeEach + public void setUp() { + foodChain = new FoodChain(); + } @Test @DisplayName("fly") diff --git a/exercises/practice/forth/.meta/template.hbs b/exercises/practice/forth/.meta/template.hbs index 73dbad194..33ef40e70 100644 --- a/exercises/practice/forth/.meta/template.hbs +++ b/exercises/practice/forth/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class {{testClassName}} { - private ForthEvaluator forthEvaluator = new ForthEvaluator(); + private ForthEvaluator forthEvaluator; + + @BeforeEach + public void setUp() { + forthEvaluator = new ForthEvaluator(); + } {{#each testCases}} {{#if disabled~}} diff --git a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java index dae1f1ada..7ef6586c8 100644 --- a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java +++ b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class ForthEvaluatorTest { - private ForthEvaluator forthEvaluator = new ForthEvaluator(); + private ForthEvaluator forthEvaluator; + + @BeforeEach + public void setUp() { + forthEvaluator = new ForthEvaluator(); + } @Test @DisplayName("parsing and numbers -> numbers just get pushed onto the stack") diff --git a/exercises/practice/grains/.meta/template.hbs b/exercises/practice/grains/.meta/template.hbs index e474812a1..bfdef63af 100644 --- a/exercises/practice/grains/.meta/template.hbs +++ b/exercises/practice/grains/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class GrainsTest { - private Grains grains = new Grains(); + private Grains grains; + + @BeforeEach + public void setUp() { + grains = new Grains(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/grains/src/test/java/GrainsTest.java b/exercises/practice/grains/src/test/java/GrainsTest.java index 233850ab7..5dde6d7fb 100644 --- a/exercises/practice/grains/src/test/java/GrainsTest.java +++ b/exercises/practice/grains/src/test/java/GrainsTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class GrainsTest { - private Grains grains = new Grains(); + private Grains grains; + + @BeforeEach + public void setUp() { + grains = new Grains(); + } @Test @DisplayName("returns the number of grains on the square -> grains on square 1") diff --git a/exercises/practice/house/.meta/template.hbs b/exercises/practice/house/.meta/template.hbs index ac98ccd90..d075c7847 100644 --- a/exercises/practice/house/.meta/template.hbs +++ b/exercises/practice/house/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class HouseTest { - private House house = new House(); + private House house; + + @BeforeEach + public void setUp() { + house = new House(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/house/src/test/java/HouseTest.java b/exercises/practice/house/src/test/java/HouseTest.java index 30736aef7..e56b4612a 100644 --- a/exercises/practice/house/src/test/java/HouseTest.java +++ b/exercises/practice/house/src/test/java/HouseTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class HouseTest { - private House house = new House(); + private House house; + + @BeforeEach + public void setUp() { + house = new House(); + } @Test @DisplayName("verse one - the house that jack built") diff --git a/exercises/practice/killer-sudoku-helper/.meta/template.hbs b/exercises/practice/killer-sudoku-helper/.meta/template.hbs index 9baecfc2b..5fee24ff8 100644 --- a/exercises/practice/killer-sudoku-helper/.meta/template.hbs +++ b/exercises/practice/killer-sudoku-helper/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class KillerSudokuHelperTest { - private KillerSudokuHelper helper = new KillerSudokuHelper(); + private KillerSudokuHelper helper; + + @BeforeEach + public void setUp() { + helper = new KillerSudokuHelper(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java index 764df1b7f..078876f1f 100644 --- a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java +++ b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ public class KillerSudokuHelperTest { - private KillerSudokuHelper helper = new KillerSudokuHelper(); + private KillerSudokuHelper helper; + + @BeforeEach + public void setUp() { + helper = new KillerSudokuHelper(); + } @Test @DisplayName("Trivial 1-digit cages -> 1") diff --git a/exercises/practice/knapsack/.meta/template.hbs b/exercises/practice/knapsack/.meta/template.hbs index 4093b69e3..ce843447e 100644 --- a/exercises/practice/knapsack/.meta/template.hbs +++ b/exercises/practice/knapsack/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class KnapsackTest { - private Knapsack knapsack = new Knapsack(); + private Knapsack knapsack; + + @BeforeEach + public void setUp() { + knapsack = new Knapsack(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/knapsack/src/test/java/KnapsackTest.java b/exercises/practice/knapsack/src/test/java/KnapsackTest.java index 70c81f3e9..4fccfaef8 100644 --- a/exercises/practice/knapsack/src/test/java/KnapsackTest.java +++ b/exercises/practice/knapsack/src/test/java/KnapsackTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ public class KnapsackTest { - private Knapsack knapsack = new Knapsack(); + private Knapsack knapsack; + + @BeforeEach + public void setUp() { + knapsack = new Knapsack(); + } @Test @DisplayName("no items") diff --git a/exercises/practice/ledger/.meta/template.hbs b/exercises/practice/ledger/.meta/template.hbs index 206aaa1c7..b5a365fcc 100644 --- a/exercises/practice/ledger/.meta/template.hbs +++ b/exercises/practice/ledger/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(LocaleExtension.class) public class LedgerTest { - private Ledger ledger = new Ledger(); + private Ledger ledger; + + @BeforeEach + public void setUp() { + ledger = new Ledger(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/ledger/src/test/java/LedgerTest.java b/exercises/practice/ledger/src/test/java/LedgerTest.java index 2f43f31d7..9b8259942 100644 --- a/exercises/practice/ledger/src/test/java/LedgerTest.java +++ b/exercises/practice/ledger/src/test/java/LedgerTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,7 +9,12 @@ @ExtendWith(LocaleExtension.class) public class LedgerTest { - private Ledger ledger = new Ledger(); + private Ledger ledger; + + @BeforeEach + public void setUp() { + ledger = new Ledger(); + } @Test @DisplayName("empty ledger") diff --git a/exercises/practice/palindrome-products/.meta/template.hbs b/exercises/practice/palindrome-products/.meta/template.hbs index 06ef3b6c8..9df94ec4e 100644 --- a/exercises/practice/palindrome-products/.meta/template.hbs +++ b/exercises/practice/palindrome-products/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,7 +11,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class {{testClassName}} { - private PalindromeCalculator palindromeCalculator = new PalindromeCalculator(); + private PalindromeCalculator palindromeCalculator; + + @BeforeEach + public void setUp() { + palindromeCalculator = new PalindromeCalculator(); + } private void checkPalindromeWithFactorsMatchesExpected(List> expectedPalindromeFactors, long expectedValueOfPalindrome, diff --git a/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java b/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java index 63c6edb21..5cf1861d3 100644 --- a/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java +++ b/exercises/practice/palindrome-products/src/test/java/PalindromeCalculatorTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,7 +11,12 @@ public class PalindromeCalculatorTest { - private PalindromeCalculator palindromeCalculator = new PalindromeCalculator(); + private PalindromeCalculator palindromeCalculator; + + @BeforeEach + public void setUp() { + palindromeCalculator = new PalindromeCalculator(); + } private void checkPalindromeWithFactorsMatchesExpected(List> expectedPalindromeFactors, long expectedValueOfPalindrome, diff --git a/exercises/practice/pascals-triangle/.meta/template.hbs b/exercises/practice/pascals-triangle/.meta/template.hbs index 59c22ad7b..197c661b9 100644 --- a/exercises/practice/pascals-triangle/.meta/template.hbs +++ b/exercises/practice/pascals-triangle/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class PascalsTriangleGeneratorTest { - private PascalsTriangleGenerator pascalsTriangleGenerator = new PascalsTriangleGenerator(); + private PascalsTriangleGenerator pascalsTriangleGenerator; + + @BeforeEach + public void setUp() { + pascalsTriangleGenerator = new PascalsTriangleGenerator(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java b/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java index 4de7be51e..052aa7d2d 100644 --- a/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java +++ b/exercises/practice/pascals-triangle/src/test/java/PascalsTriangleGeneratorTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class PascalsTriangleGeneratorTest { - private PascalsTriangleGenerator pascalsTriangleGenerator = new PascalsTriangleGenerator(); + private PascalsTriangleGenerator pascalsTriangleGenerator; + + @BeforeEach + public void setUp() { + pascalsTriangleGenerator = new PascalsTriangleGenerator(); + } @Test @DisplayName("zero rows") diff --git a/exercises/practice/protein-translation/.meta/template.hbs b/exercises/practice/protein-translation/.meta/template.hbs index 378661e91..04fb2bc95 100644 --- a/exercises/practice/protein-translation/.meta/template.hbs +++ b/exercises/practice/protein-translation/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class ProteinTranslatorTest { - private ProteinTranslator proteinTranslator = new ProteinTranslator(); + private ProteinTranslator proteinTranslator; + + @BeforeEach + public void setUp() { + proteinTranslator = new ProteinTranslator(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java index 8aa023327..5be4e528e 100644 --- a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java +++ b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class ProteinTranslatorTest { - private ProteinTranslator proteinTranslator = new ProteinTranslator(); + private ProteinTranslator proteinTranslator; + + @BeforeEach + public void setUp() { + proteinTranslator = new ProteinTranslator(); + } @Test @DisplayName("Empty RNA sequence results in no proteins") diff --git a/exercises/practice/run-length-encoding/.meta/template.hbs b/exercises/practice/run-length-encoding/.meta/template.hbs index f9a824398..9075ce8c1 100644 --- a/exercises/practice/run-length-encoding/.meta/template.hbs +++ b/exercises/practice/run-length-encoding/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class RunLengthEncodingTest { - private RunLengthEncoding runLengthEncoding = new RunLengthEncoding(); + private RunLengthEncoding runLengthEncoding; + + @BeforeEach + public void setUp() { + runLengthEncoding = new RunLengthEncoding(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java index 23dff968e..a084d1dc3 100644 --- a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java +++ b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class RunLengthEncodingTest { - private RunLengthEncoding runLengthEncoding = new RunLengthEncoding(); + private RunLengthEncoding runLengthEncoding; + + @BeforeEach + public void setUp() { + runLengthEncoding = new RunLengthEncoding(); + } @Test @DisplayName("run-length encode a string -> empty string") diff --git a/exercises/practice/satellite/.meta/template.hbs b/exercises/practice/satellite/.meta/template.hbs index 499e08709..4fcd4e991 100644 --- a/exercises/practice/satellite/.meta/template.hbs +++ b/exercises/practice/satellite/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class {{testClassName}} { - private Satellite satellite = new Satellite(); + private Satellite satellite; + + @BeforeEach + public void setUp() { + satellite = new Satellite(); + } {{#each testCases}} {{#if disabled~}} diff --git a/exercises/practice/satellite/src/test/java/SatelliteTest.java b/exercises/practice/satellite/src/test/java/SatelliteTest.java index 2341a15cd..ef36b6a80 100644 --- a/exercises/practice/satellite/src/test/java/SatelliteTest.java +++ b/exercises/practice/satellite/src/test/java/SatelliteTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class SatelliteTest { - private Satellite satellite = new Satellite(); + private Satellite satellite; + + @BeforeEach + public void setUp() { + satellite = new Satellite(); + } @Test @DisplayName("Empty tree") diff --git a/exercises/practice/simple-cipher/.meta/template.hbs b/exercises/practice/simple-cipher/.meta/template.hbs index 5f72c42c4..3d1c4e7e7 100644 --- a/exercises/practice/simple-cipher/.meta/template.hbs +++ b/exercises/practice/simple-cipher/.meta/template.hbs @@ -8,11 +8,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class {{testClassName}} { private Cipher randomKeyCipher; - private Cipher substitutionCipher = new Cipher("abcdefghij"); + private Cipher substitutionCipher; @BeforeEach public void setup() { randomKeyCipher = new Cipher(); + substitutionCipher = new Cipher("abcdefghij"); } {{#each testCases}} diff --git a/exercises/practice/simple-cipher/src/test/java/SimpleCipherTest.java b/exercises/practice/simple-cipher/src/test/java/SimpleCipherTest.java index 8c2c66a08..d4c4bf524 100644 --- a/exercises/practice/simple-cipher/src/test/java/SimpleCipherTest.java +++ b/exercises/practice/simple-cipher/src/test/java/SimpleCipherTest.java @@ -8,11 +8,12 @@ public class SimpleCipherTest { private Cipher randomKeyCipher; - private Cipher substitutionCipher = new Cipher("abcdefghij"); + private Cipher substitutionCipher; @BeforeEach public void setup() { randomKeyCipher = new Cipher(); + substitutionCipher = new Cipher("abcdefghij"); } @Test diff --git a/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs b/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs index a13ff8cce..ac882e003 100644 --- a/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs +++ b/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class StateOfTicTacToeTest { - private StateOfTicTacToe stateOfTicTacToe = new StateOfTicTacToe(); + private StateOfTicTacToe stateOfTicTacToe; + + @BeforeEach + public void setUp() { + stateOfTicTacToe = new StateOfTicTacToe(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java index c3bbc964f..a52320570 100644 --- a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java +++ b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ public class StateOfTicTacToeTest { - private StateOfTicTacToe stateOfTicTacToe = new StateOfTicTacToe(); + private StateOfTicTacToe stateOfTicTacToe; + + @BeforeEach + public void setUp() { + stateOfTicTacToe = new StateOfTicTacToe(); + } @Test @DisplayName("Won games -> Finished game where X won via left column victory") diff --git a/exercises/practice/twelve-days/.meta/template.hbs b/exercises/practice/twelve-days/.meta/template.hbs index 422d9c124..9a2f4a646 100644 --- a/exercises/practice/twelve-days/.meta/template.hbs +++ b/exercises/practice/twelve-days/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; public class TwelveDaysTest { - private TwelveDays twelveDays = new TwelveDays(); + private TwelveDays twelveDays; + + @BeforeEach + public void setUp() { + twelveDays = new TwelveDays(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java index e8b6388fb..76637c618 100644 --- a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java +++ b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -6,7 +7,12 @@ public class TwelveDaysTest { - private TwelveDays twelveDays = new TwelveDays(); + private TwelveDays twelveDays; + + @BeforeEach + public void setUp() { + twelveDays = new TwelveDays(); + } @Test @DisplayName("verse -> first day a partridge in a pear tree") diff --git a/exercises/practice/variable-length-quantity/.meta/template.hbs b/exercises/practice/variable-length-quantity/.meta/template.hbs index 4e8eee2ba..f204da297 100644 --- a/exercises/practice/variable-length-quantity/.meta/template.hbs +++ b/exercises/practice/variable-length-quantity/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class VariableLengthQuantityTest { - private VariableLengthQuantity variableLengthQuantity = new VariableLengthQuantity(); + private VariableLengthQuantity variableLengthQuantity; + + @BeforeEach + public void setUp() { + variableLengthQuantity = new VariableLengthQuantity(); + } {{#each testCases}} {{#if disabled}} diff --git a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java index f6b10f5fe..5352f649f 100644 --- a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java +++ b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,7 +10,12 @@ public class VariableLengthQuantityTest { - private VariableLengthQuantity variableLengthQuantity = new VariableLengthQuantity(); + private VariableLengthQuantity variableLengthQuantity; + + @BeforeEach + public void setUp() { + variableLengthQuantity = new VariableLengthQuantity(); + } @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> zero") diff --git a/exercises/practice/wordy/.meta/template.hbs b/exercises/practice/wordy/.meta/template.hbs index 3aa7805f3..49001fed6 100644 --- a/exercises/practice/wordy/.meta/template.hbs +++ b/exercises/practice/wordy/.meta/template.hbs @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class WordProblemSolverTest { - private WordProblemSolver solver = new WordProblemSolver(); + private WordProblemSolver solver; + + @BeforeEach + public void setUp() { + solver = new WordProblemSolver(); + } {{#each testCases}} {{#if disabled~}} diff --git a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java index 45f6eeb3e..a4a0f2a19 100644 --- a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java +++ b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java @@ -1,3 +1,4 @@ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,7 +8,12 @@ public class WordProblemSolverTest { - private WordProblemSolver solver = new WordProblemSolver(); + private WordProblemSolver solver; + + @BeforeEach + public void setUp() { + solver = new WordProblemSolver(); + } @Test @DisplayName("just a number") diff --git a/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java index df05a285c..d8251e35f 100644 --- a/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java +++ b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java @@ -2270,11 +2270,16 @@ private void registerHelpers() { java.util.List lines = new java.util.ArrayList<>(); lines.add("CircularBuffer buffer = new CircularBuffer<>(" + capacity + ");"); - if (ops.isArray()) { + if (ops.isArray() && !ops.isEmpty()) { + lines.add(""); + boolean prevWasException = false; for (JsonNode op : ops) { String operation = op.path("operation").asText(); boolean shouldSucceed = op.path("should_succeed").asBoolean(true); - lines.add(""); + boolean isException = ("write".equals(operation) || "read".equals(operation)) && !shouldSucceed; + if ((isException && lines.size() > 2) || prevWasException) { + lines.add(""); + } switch (operation) { case "write" -> { int item = op.path("item").asInt(); @@ -2304,6 +2309,7 @@ private void registerHelpers() { lines.add("buffer.clear();"); } } + prevWasException = isException; } } return String.join("\n ", lines); From 8e2ce44bb5b5af68a11215cf0fb4f4d59fcb103e Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 4 Dec 2026 01:13:11 +0530 Subject: [PATCH 3/3] Remove empty from the end and start of a method --- .../src/test/java/AffineCipherTest.java | 32 ---------- .../src/test/java/BaseConverterTest.java | 42 ------------- .../src/test/java/AlphameticsTest.java | 20 ------ .../src/test/java/BafflingBirthdaysTest.java | 34 ---------- .../src/test/java/BinarySearchTest.java | 22 ------- .../src/test/java/DnDCharacterTest.java | 38 ------------ .../dominoes/src/test/java/DominoesTest.java | 13 ---- .../src/test/java/FoodChainTest.java | 20 ------ .../grains/src/test/java/GrainsTest.java | 22 ------- .../hamming/src/test/java/HammingTest.java | 18 ------ .../house/src/test/java/HouseTest.java | 28 --------- .../java/IntergalacticTransmissionTest.java | 52 ---------------- .../src/test/java/KillerSudokuHelperTest.java | 26 -------- .../LargestSeriesProductCalculatorTest.java | 20 ------ .../src/test/java/NucleotideCounterTest.java | 10 --- .../src/test/java/PhoneNumberTest.java | 36 ----------- .../src/test/java/PiecingItTogetherTest.java | 14 ----- .../src/test/java/ProteinTranslatorTest.java | 62 ------------------- .../test/java/QueenAttackCalculatorTest.java | 26 -------- .../src/test/java/RelativeDistanceTest.java | 7 --- .../src/test/java/RunLengthEncodingTest.java | 26 -------- .../test/java/SpiralMatrixBuilderTest.java | 12 ---- .../src/test/java/StateOfTicTacToeTest.java | 54 ---------------- .../src/test/java/TwelveDaysTest.java | 30 --------- .../src/test/java/TwoBucketTest.java | 18 ------ .../test/java/VariableLengthQuantityTest.java | 52 ---------------- .../src/test/java/WordProblemSolverTest.java | 46 -------------- .../src/test/java/ZebraPuzzleTest.java | 2 - .../service/TemplateRenderer.java | 37 +++++++---- .../testgenerator/TemplateRendererTest.java | 38 ++++++++++++ 30 files changed, 63 insertions(+), 794 deletions(-) diff --git a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java index 1aab8f84a..339503cc7 100644 --- a/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java +++ b/exercises/practice/affine-cipher/src/test/java/AffineCipherTest.java @@ -18,178 +18,146 @@ public void setUp() { @Test @DisplayName("encode -> encode yes") public void encodeEncodeYes() { - assertThat(affineCipher.encode( "yes", 5, 7)) .isEqualTo("xbt"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode no") public void encodeEncodeNo() { - assertThat(affineCipher.encode( "no", 15, 18)) .isEqualTo("fu"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode OMG") public void encodeEncodeOmg() { - assertThat(affineCipher.encode( "OMG", 21, 3)) .isEqualTo("lvz"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode O M G") public void encodeEncodeOMG() { - assertThat(affineCipher.encode( "O M G", 25, 47)) .isEqualTo("hjp"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode mindblowingly") public void encodeEncodeMindblowingly() { - assertThat(affineCipher.encode( "mindblowingly", 11, 15)) .isEqualTo("rzcwa gnxzc dgt"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode numbers") public void encodeEncodeNumbers() { - assertThat(affineCipher.encode( "Testing,1 2 3, testing.", 3, 4)) .isEqualTo("jqgjc rw123 jqgjc rw"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode deep thought") public void encodeEncodeDeepThought() { - assertThat(affineCipher.encode( "Truth is fiction.", 5, 17)) .isEqualTo("iynia fdqfb ifje"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode all the letters") public void encodeEncodeAllTheLetters() { - assertThat(affineCipher.encode( "The quick brown fox jumps over the lazy dog.", 17, 33)) .isEqualTo("swxtj npvyk lruol iejdc blaxk swxmh qzglf"); - } @Disabled("Remove to run test") @Test @DisplayName("encode -> encode with a not coprime to m") public void encodeEncodeWithANotCoprimeToM() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> affineCipher.encode( "This is a test.", 6, 17)) .withMessage("Error: keyA and alphabet size must be coprime."); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode exercism") public void decodeDecodeExercism() { - assertThat(affineCipher.decode( "tytgn fjr", 3, 7)) .isEqualTo("exercism"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode a sentence") public void decodeDecodeASentence() { - assertThat(affineCipher.decode( "qdwju nqcro muwhn odqun oppmd aunwd o", 19, 16)) .isEqualTo("anobstacleisoftenasteppingstone"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode numbers") public void decodeDecodeNumbers() { - assertThat(affineCipher.decode( "odpoz ub123 odpoz ub", 25, 7)) .isEqualTo("testing123testing"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode all the letters") public void decodeDecodeAllTheLetters() { - assertThat(affineCipher.decode( "swxtj npvyk lruol iejdc blaxk swxmh qzglf", 17, 33)) .isEqualTo("thequickbrownfoxjumpsoverthelazydog"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode with no spaces in input") public void decodeDecodeWithNoSpacesInInput() { - assertThat(affineCipher.decode( "swxtjnpvyklruoliejdcblaxkswxmhqzglf", 17, 33)) .isEqualTo("thequickbrownfoxjumpsoverthelazydog"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode with too many spaces") public void decodeDecodeWithTooManySpaces() { - assertThat(affineCipher.decode( "vszzm cly yd cg qdp", 15, 16)) .isEqualTo("jollygreengiant"); - } @Disabled("Remove to run test") @Test @DisplayName("decode -> decode with a not coprime to m") public void decodeDecodeWithANotCoprimeToM() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> affineCipher.decode( "Test", 13, 5)) .withMessage("Error: keyA and alphabet size must be coprime."); - } } diff --git a/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java b/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java index dbea68bf6..ecb7fd184 100644 --- a/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java +++ b/exercises/practice/all-your-base/src/test/java/BaseConverterTest.java @@ -10,51 +10,42 @@ public class BaseConverterTest { @Test @DisplayName("single bit one to decimal") public void singleBitOneToDecimal() { - assertThat(new BaseConverter(2, new int[]{1}) .convertToBase(10)) .containsExactly(1); - } @Disabled("Remove to run test") @Test @DisplayName("binary to single decimal") public void binaryToSingleDecimal() { - assertThat(new BaseConverter(2, new int[]{1, 0, 1}) .convertToBase(10)) .containsExactly(5); - } @Disabled("Remove to run test") @Test @DisplayName("single decimal to binary") public void singleDecimalToBinary() { - assertThat(new BaseConverter(10, new int[]{5}) .convertToBase(2)) .containsExactly(1, 0, 1); - } @Disabled("Remove to run test") @Test @DisplayName("binary to multiple decimal") public void binaryToMultipleDecimal() { - assertThat(new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}) .convertToBase(10)) .containsExactly(4, 2); - } @Disabled("Remove to run test") @Test @DisplayName("decimal to binary") public void decimalToBinary() { - assertThat(new BaseConverter(10, new int[]{4, 2}) .convertToBase(2)) .containsExactly( @@ -64,192 +55,159 @@ public void decimalToBinary() { 0, 1, 0); - } @Disabled("Remove to run test") @Test @DisplayName("trinary to hexadecimal") public void trinaryToHexadecimal() { - assertThat(new BaseConverter(3, new int[]{1, 1, 2, 0}) .convertToBase(16)) .containsExactly(2, 10); - } @Disabled("Remove to run test") @Test @DisplayName("hexadecimal to trinary") public void hexadecimalToTrinary() { - assertThat(new BaseConverter(16, new int[]{2, 10}) .convertToBase(3)) .containsExactly(1, 1, 2, 0); - } @Disabled("Remove to run test") @Test @DisplayName("15-bit integer") public void test15BitInteger() { - assertThat(new BaseConverter(97, new int[]{3, 46, 60}) .convertToBase(73)) .containsExactly(6, 10, 45); - } @Disabled("Remove to run test") @Test @DisplayName("empty list") public void emptyList() { - assertThat(new BaseConverter(2, new int[]{}) .convertToBase(10)) .containsExactly(0); - } @Disabled("Remove to run test") @Test @DisplayName("single zero") public void singleZero() { - assertThat(new BaseConverter(10, new int[]{0}) .convertToBase(2)) .containsExactly(0); - } @Disabled("Remove to run test") @Test @DisplayName("multiple zeros") public void multipleZeros() { - assertThat(new BaseConverter(10, new int[]{0, 0, 0}) .convertToBase(2)) .containsExactly(0); - } @Disabled("Remove to run test") @Test @DisplayName("leading zeros") public void leadingZeros() { - assertThat(new BaseConverter(7, new int[]{0, 6, 0}) .convertToBase(10)) .containsExactly(4, 2); - } @Disabled("Remove to run test") @Test @DisplayName("input base is one") public void inputBaseIsOne() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(1, new int[]{0}) .convertToBase(10)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("input base is zero") public void inputBaseIsZero() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(0, new int[]{}) .convertToBase(10)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("input base is negative") public void inputBaseIsNegative() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(-2, new int[]{1}) .convertToBase(10)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("negative digit") public void negativeDigit() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(2, new int[]{1, -1, 1, 0, 1, 0}) .convertToBase(10)) .withMessage("Digits may not be negative."); - } @Disabled("Remove to run test") @Test @DisplayName("invalid positive digit") public void invalidPositiveDigit() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(2, new int[]{1, 2, 1, 0, 1, 0}) .convertToBase(10)) .withMessage("All digits must be strictly less than the base."); - } @Disabled("Remove to run test") @Test @DisplayName("output base is one") public void outputBaseIsOne() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0}) .convertToBase(1)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("output base is zero") public void outputBaseIsZero() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(10, new int[]{7}) .convertToBase(0)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("output base is negative") public void outputBaseIsNegative() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(2, new int[]{1}) .convertToBase(-7)) .withMessage("Bases must be at least 2."); - } @Disabled("Remove to run test") @Test @DisplayName("both bases are negative") public void bothBasesAreNegative() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new BaseConverter(-2, new int[]{1}) .convertToBase(-7)) .withMessage("Bases must be at least 2."); - } } diff --git a/exercises/practice/alphametics/src/test/java/AlphameticsTest.java b/exercises/practice/alphametics/src/test/java/AlphameticsTest.java index 142b3b411..0c2da184f 100644 --- a/exercises/practice/alphametics/src/test/java/AlphameticsTest.java +++ b/exercises/practice/alphametics/src/test/java/AlphameticsTest.java @@ -13,55 +13,46 @@ public class AlphameticsTest { @Test @DisplayName("puzzle with three letters") public void puzzleWithThreeLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("I + BB == ILL").solve()) .isEqualTo(Map.ofEntries( entry('I', 1), entry('B', 9), entry('L', 0) )); - } @Disabled("Remove to run test") @Test @DisplayName("solution must have unique value for each letter") public void solutionMustHaveUniqueValueForEachLetter() throws UnsolvablePuzzleException { - assertThatExceptionOfType(UnsolvablePuzzleException.class) .isThrownBy(() -> new Alphametics("A == B").solve()); - } @Disabled("Remove to run test") @Test @DisplayName("leading zero solution is invalid") public void leadingZeroSolutionIsInvalid() throws UnsolvablePuzzleException { - assertThatExceptionOfType(UnsolvablePuzzleException.class) .isThrownBy(() -> new Alphametics("ACA + DD == BD").solve()); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with two digits final carry") public void puzzleWithTwoDigitsFinalCarry() throws UnsolvablePuzzleException { - assertThat(new Alphametics("A + A + A + A + A + A + A + A + A + A + A + B == BCC").solve()) .isEqualTo(Map.ofEntries( entry('A', 9), entry('B', 1), entry('C', 0) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with four letters") public void puzzleWithFourLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("AS + A == MOM").solve()) .isEqualTo(Map.ofEntries( entry('A', 9), @@ -69,14 +60,12 @@ public void puzzleWithFourLetters() throws UnsolvablePuzzleException { entry('M', 1), entry('O', 0) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with six letters") public void puzzleWithSixLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("NO + NO + TOO == LATE").solve()) .isEqualTo(Map.ofEntries( entry('N', 7), @@ -86,14 +75,12 @@ public void puzzleWithSixLetters() throws UnsolvablePuzzleException { entry('A', 0), entry('E', 2) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with seven letters") public void puzzleWithSevenLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("HE + SEES + THE == LIGHT").solve()) .isEqualTo(Map.ofEntries( entry('E', 4), @@ -104,14 +91,12 @@ public void puzzleWithSevenLetters() throws UnsolvablePuzzleException { entry('S', 9), entry('T', 7) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with eight letters") public void puzzleWithEightLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("SEND + MORE == MONEY").solve()) .isEqualTo(Map.ofEntries( entry('S', 9), @@ -123,14 +108,12 @@ public void puzzleWithEightLetters() throws UnsolvablePuzzleException { entry('R', 8), entry('Y', 2) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with ten letters") public void puzzleWithTenLetters() throws UnsolvablePuzzleException { - assertThat(new Alphametics("AND + A + STRONG + OFFENSE + AS + A + GOOD == DEFENSE").solve()) .isEqualTo(Map.ofEntries( entry('A', 5), @@ -144,14 +127,12 @@ public void puzzleWithTenLetters() throws UnsolvablePuzzleException { entry('S', 6), entry('T', 9) )); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with ten letters and 199 addends") public void puzzleWithTenLettersAnd199Addends() throws UnsolvablePuzzleException { - assertThat(new Alphametics("THIS + A + FIRE + THEREFORE + FOR + ALL + HISTORIES + I + TELL + A + " + "TALE + THAT + FALSIFIES + ITS + TITLE + TIS + A + LIE + THE + TALE + " + "OF + THE + LAST + FIRE + HORSES + LATE + AFTER + THE + FIRST + FATHERS " @@ -185,7 +166,6 @@ public void puzzleWithTenLettersAnd199Addends() throws UnsolvablePuzzleException entry('S', 4), entry('T', 9) )); - } } diff --git a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java index b77c11f7e..33ac400ec 100644 --- a/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java +++ b/exercises/practice/baffling-birthdays/src/test/java/BafflingBirthdaysTest.java @@ -21,73 +21,60 @@ public void setUp() { @Test @DisplayName("shared birthday -> one birthdate") public void sharedBirthdayOneBirthdate() { - List birthdates = List.of(LocalDate.parse("2000-01-01")); assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> two birthdates with same year, month, and day") public void sharedBirthdayTwoBirthdatesWithSameYearMonthAndDay() { - List birthdates = List.of(LocalDate.parse("2000-01-01"), LocalDate.parse("2000-01-01")); assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> two birthdates with same year and month, but different day") public void sharedBirthdayTwoBirthdatesWithSameYearAndMonthButDifferentDay() { - List birthdates = List.of(LocalDate.parse("2012-05-09"), LocalDate.parse("2012-05-17")); assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> two birthdates with same month and day, but different year") public void sharedBirthdayTwoBirthdatesWithSameMonthAndDayButDifferentYear() { - List birthdates = List.of(LocalDate.parse("1999-10-23"), LocalDate.parse("1988-10-23")); assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> two birthdates with same year, but different month and day") public void sharedBirthdayTwoBirthdatesWithSameYearButDifferentMonthAndDay() { - List birthdates = List.of(LocalDate.parse("2007-12-19"), LocalDate.parse("2007-04-27")); assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> two birthdates with different year, month, and day") public void sharedBirthdayTwoBirthdatesWithDifferentYearMonthAndDay() { - List birthdates = List.of(LocalDate.parse("1997-08-04"), LocalDate.parse("1963-11-23")); assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> multiple birthdates without shared birthday") public void sharedBirthdayMultipleBirthdatesWithoutSharedBirthday() { - List birthdates = List.of( LocalDate.parse("1966-07-29"), LocalDate.parse("1977-02-12"), @@ -96,14 +83,12 @@ public void sharedBirthdayMultipleBirthdatesWithoutSharedBirthday() { ); assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> multiple birthdates with one shared birthday") public void sharedBirthdayMultipleBirthdatesWithOneSharedBirthday() { - List birthdates = List.of( LocalDate.parse("1966-07-29"), LocalDate.parse("1977-02-12"), @@ -112,14 +97,12 @@ public void sharedBirthdayMultipleBirthdatesWithOneSharedBirthday() { ); assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("shared birthday -> multiple birthdates with more than one shared birthday") public void sharedBirthdayMultipleBirthdatesWithMoreThanOneSharedBirthday() { - List birthdates = List.of( LocalDate.parse("1966-07-29"), LocalDate.parse("1977-02-12"), @@ -129,86 +112,69 @@ public void sharedBirthdayMultipleBirthdatesWithMoreThanOneSharedBirthday() { ); assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("random birthdates -> generate requested number of birthdates") public void randomBirthdatesGenerateRequestedNumberOfBirthdates() { - int groupSize = 50; assertThat(birthdays.randomBirthdates(groupSize).size()).isEqualTo(groupSize); - } @Disabled("Remove to run test") @Test @DisplayName("random birthdates -> years are not leap years") public void randomBirthdatesYearsAreNotLeapYears() { - assertThat(birthdays.randomBirthdates(100)).noneMatch(LocalDate::isLeapYear); - } @Disabled("Remove to run test") @Test @DisplayName("random birthdates -> months are random") public void randomBirthdatesMonthsAreRandom() { - assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getMonth).distinct()) .hasSizeGreaterThanOrEqualTo(7); - } @Disabled("Remove to run test") @Test @DisplayName("random birthdates -> days are random") public void randomBirthdatesDaysAreRandom() { - assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getDayOfMonth).distinct()) .hasSizeGreaterThanOrEqualTo(11); - } @Disabled("Remove to run test") @Test @DisplayName("estimated probability of at least one shared birthday -> for one person") public void estimatedProbabilityOfAtLeastOneSharedBirthdayForOnePerson() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(1)) .isEqualTo(0.0); - } @Disabled("Remove to run test") @Test @DisplayName("estimated probability of at least one shared birthday -> among ten people") public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTenPeople() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(10)) .isCloseTo(11.694818, offset(1.0)); - } @Disabled("Remove to run test") @Test @DisplayName("estimated probability of at least one shared birthday -> among twenty-three people") public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongTwentyThreePeo() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(23)) .isCloseTo(50.729723, offset(1.0)); - } @Disabled("Remove to run test") @Test @DisplayName("estimated probability of at least one shared birthday -> among seventy people") public void estimatedProbabilityOfAtLeastOneSharedBirthdayAmongSeventyPeople() { - assertThat(birthdays.estimatedProbabilityOfSharedBirthday(70)) .isCloseTo(99.915958, offset(1.0)); - } } diff --git a/exercises/practice/binary-search/src/test/java/BinarySearchTest.java b/exercises/practice/binary-search/src/test/java/BinarySearchTest.java index 75ddd26f3..ac37845cb 100644 --- a/exercises/practice/binary-search/src/test/java/BinarySearchTest.java +++ b/exercises/practice/binary-search/src/test/java/BinarySearchTest.java @@ -12,51 +12,42 @@ public class BinarySearchTest { @Test @DisplayName("finds a value in an array with one element") public void findsAValueInAnArrayWithOneElement() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of(6)) .indexOf(6)) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("finds a value in the middle of an array") public void findsAValueInTheMiddleOfAnArray() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(6)) .isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("finds a value at the beginning of an array") public void findsAValueAtTheBeginningOfAnArray() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(1)) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("finds a value at the end of an array") public void findsAValueAtTheEndOfAnArray() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(11)) .isEqualTo(6); - } @Disabled("Remove to run test") @Test @DisplayName("finds a value in an array of odd length") public void findsAValueInAnArrayOfOddLength() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of( 1, 3, @@ -74,14 +65,12 @@ public void findsAValueInAnArrayOfOddLength() throws ValueNotFoundException { )) .indexOf(144)) .isEqualTo(9); - } @Disabled("Remove to run test") @Test @DisplayName("finds a value in an array of even length") public void findsAValueInAnArrayOfEvenLength() throws ValueNotFoundException { - assertThat(new BinarySearch(List.of( 1, 3, @@ -98,67 +87,56 @@ public void findsAValueInAnArrayOfEvenLength() throws ValueNotFoundException { )) .indexOf(21)) .isEqualTo(5); - } @Disabled("Remove to run test") @Test @DisplayName("identifies that a value is not included in the array") public void identifiesThatAValueIsNotIncludedInTheArray() throws ValueNotFoundException { - assertThatExceptionOfType(ValueNotFoundException.class) .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(7)) .withMessage("Value not in array"); - } @Disabled("Remove to run test") @Test @DisplayName("a value smaller than the array's smallest value is not found") public void aValueSmallerThanTheArraySSmallestValueIsNotFound() throws ValueNotFoundException { - assertThatExceptionOfType(ValueNotFoundException.class) .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(0)) .withMessage("Value not in array"); - } @Disabled("Remove to run test") @Test @DisplayName("a value larger than the array's largest value is not found") public void aValueLargerThanTheArraySLargestValueIsNotFound() throws ValueNotFoundException { - assertThatExceptionOfType(ValueNotFoundException.class) .isThrownBy(() -> new BinarySearch(List.of(1, 3, 4, 6, 8, 9, 11)) .indexOf(13)) .withMessage("Value not in array"); - } @Disabled("Remove to run test") @Test @DisplayName("nothing is found in an empty array") public void nothingIsFoundInAnEmptyArray() throws ValueNotFoundException { - assertThatExceptionOfType(ValueNotFoundException.class) .isThrownBy(() -> new BinarySearch(List.of()) .indexOf(1)) .withMessage("Value not in array"); - } @Disabled("Remove to run test") @Test @DisplayName("nothing is found when the left and right bounds cross") public void nothingIsFoundWhenTheLeftAndRightBoundsCross() throws ValueNotFoundException { - assertThatExceptionOfType(ValueNotFoundException.class) .isThrownBy(() -> new BinarySearch(List.of(1, 2)) .indexOf(0)) .withMessage("Value not in array"); - } } diff --git a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java index 36ae316f8..e7d61aba6 100644 --- a/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java +++ b/exercises/practice/dnd-character/src/test/java/DnDCharacterTest.java @@ -17,179 +17,144 @@ public void setUp() { @Test @DisplayName("ability modifier -> ability modifier for score 3 is -4") public void abilityModifierAbilityModifierForScore3Is4() { - assertThat(dndCharacter.modifier(3)) .isEqualTo(-4); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 4 is -3") public void abilityModifierAbilityModifierForScore4Is3() { - assertThat(dndCharacter.modifier(4)) .isEqualTo(-3); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 5 is -3") public void abilityModifierAbilityModifierForScore5Is3() { - assertThat(dndCharacter.modifier(5)) .isEqualTo(-3); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 6 is -2") public void abilityModifierAbilityModifierForScore6Is2() { - assertThat(dndCharacter.modifier(6)) .isEqualTo(-2); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 7 is -2") public void abilityModifierAbilityModifierForScore7Is2() { - assertThat(dndCharacter.modifier(7)) .isEqualTo(-2); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 8 is -1") public void abilityModifierAbilityModifierForScore8Is1() { - assertThat(dndCharacter.modifier(8)) .isEqualTo(-1); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 9 is -1") public void abilityModifierAbilityModifierForScore9Is1() { - assertThat(dndCharacter.modifier(9)) .isEqualTo(-1); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 10 is 0") public void abilityModifierAbilityModifierForScore10Is0() { - assertThat(dndCharacter.modifier(10)) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 11 is 0") public void abilityModifierAbilityModifierForScore11Is0() { - assertThat(dndCharacter.modifier(11)) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 12 is +1") public void abilityModifierAbilityModifierForScore12Is1() { - assertThat(dndCharacter.modifier(12)) .isEqualTo(1); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 13 is +1") public void abilityModifierAbilityModifierForScore13Is1() { - assertThat(dndCharacter.modifier(13)) .isEqualTo(1); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 14 is +2") public void abilityModifierAbilityModifierForScore14Is2() { - assertThat(dndCharacter.modifier(14)) .isEqualTo(2); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 15 is +2") public void abilityModifierAbilityModifierForScore15Is2() { - assertThat(dndCharacter.modifier(15)) .isEqualTo(2); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 16 is +3") public void abilityModifierAbilityModifierForScore16Is3() { - assertThat(dndCharacter.modifier(16)) .isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 17 is +3") public void abilityModifierAbilityModifierForScore17Is3() { - assertThat(dndCharacter.modifier(17)) .isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("ability modifier -> ability modifier for score 18 is +4") public void abilityModifierAbilityModifierForScore18Is4() { - assertThat(dndCharacter.modifier(18)) .isEqualTo(4); - } @Disabled("Remove to run test") @Test @DisplayName("random ability is within range") public void randomAbilityIsWithinRange() { - for (int i = 0; i < 1000; i++) { int score = dndCharacter.ability(dndCharacter.rollDice()); assertThat(score).isGreaterThan(2).isLessThan(19); } - } @Disabled("Remove to run test") @Test @DisplayName("random character is valid") public void randomCharacterIsValid() { - for (int i = 0; i < 1000; i++) { DnDCharacter character = new DnDCharacter(); assertThat(character.getStrength()).isGreaterThan(2).isLessThan(19); @@ -200,14 +165,12 @@ public void randomCharacterIsValid() { assertThat(character.getCharisma()).isGreaterThan(2).isLessThan(19); assertThat(character.getHitpoints()).isEqualTo(10 + character.modifier(character.getConstitution())); } - } @Disabled("Remove to run test") @Test @DisplayName("each ability is only calculated once") public void eachAbilityIsOnlyCalculatedOnce() { - DnDCharacter character = new DnDCharacter(); assertThat(character.getStrength()).isEqualTo(character.getStrength()); assertThat(character.getDexterity()).isEqualTo(character.getDexterity()); @@ -215,7 +178,6 @@ public void eachAbilityIsOnlyCalculatedOnce() { assertThat(character.getIntelligence()).isEqualTo(character.getIntelligence()); assertThat(character.getWisdom()).isEqualTo(character.getWisdom()); assertThat(character.getCharisma()).isEqualTo(character.getCharisma()); - } } diff --git a/exercises/practice/dominoes/src/test/java/DominoesTest.java b/exercises/practice/dominoes/src/test/java/DominoesTest.java index 6c61295cf..3fea6a4bb 100644 --- a/exercises/practice/dominoes/src/test/java/DominoesTest.java +++ b/exercises/practice/dominoes/src/test/java/DominoesTest.java @@ -18,7 +18,6 @@ public void emptyInputEmptyOutput() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -30,7 +29,6 @@ public void singletonInputSingletonOutput() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -43,7 +41,6 @@ public void singletonThatCanTBeChained() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } @Disabled("Remove to run test") @@ -59,7 +56,6 @@ public void threeElements() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -75,7 +71,6 @@ public void canReverseDominoes() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -92,7 +87,6 @@ public void canTBeChained() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } @Disabled("Remove to run test") @@ -105,7 +99,6 @@ public void disconnectedSimple() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } @Disabled("Remove to run test") @@ -123,7 +116,6 @@ public void disconnectedDoubleLoop() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } @Disabled("Remove to run test") @@ -141,7 +133,6 @@ public void disconnectedSingleIsolated() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } @Disabled("Remove to run test") @@ -159,7 +150,6 @@ public void needBacktrack() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -178,7 +168,6 @@ public void separateLoops() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -200,7 +189,6 @@ public void nineElements() throws ChainNotFoundException { List chain = dominoes.formChain(dominoesList); assertValidChain(dominoesList, chain); - } @Disabled("Remove to run test") @@ -220,7 +208,6 @@ public void separateThreeDominoLoops() throws ChainNotFoundException { assertThatExceptionOfType(ChainNotFoundException.class) .isThrownBy(() -> dominoes.formChain(dominoesList)) .withMessage("No domino chain found."); - } private void assertValidChain(List inputDominoes, List outputDominoes) { diff --git a/exercises/practice/food-chain/src/test/java/FoodChainTest.java b/exercises/practice/food-chain/src/test/java/FoodChainTest.java index 8747ee595..861b6fd44 100644 --- a/exercises/practice/food-chain/src/test/java/FoodChainTest.java +++ b/exercises/practice/food-chain/src/test/java/FoodChainTest.java @@ -17,19 +17,16 @@ public void setUp() { @Test @DisplayName("fly") public void fly() { - assertThat(foodChain.verse(1)) .isEqualTo("I know an old lady who swallowed a fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("spider") public void spider() { - assertThat(foodChain.verse(2)) .isEqualTo("I know an old lady who swallowed a spider." + "\n" @@ -38,14 +35,12 @@ public void spider() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("bird") public void bird() { - assertThat(foodChain.verse(3)) .isEqualTo("I know an old lady who swallowed a bird." + "\n" @@ -57,14 +52,12 @@ public void bird() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("cat") public void cat() { - assertThat(foodChain.verse(4)) .isEqualTo("I know an old lady who swallowed a cat." + "\n" @@ -78,14 +71,12 @@ public void cat() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("dog") public void dog() { - assertThat(foodChain.verse(5)) .isEqualTo("I know an old lady who swallowed a dog." + "\n" @@ -101,14 +92,12 @@ public void dog() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("goat") public void goat() { - assertThat(foodChain.verse(6)) .isEqualTo("I know an old lady who swallowed a goat." + "\n" @@ -126,14 +115,12 @@ public void goat() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("cow") public void cow() { - assertThat(foodChain.verse(7)) .isEqualTo("I know an old lady who swallowed a cow." + "\n" @@ -153,26 +140,22 @@ public void cow() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("horse") public void horse() { - assertThat(foodChain.verse(8)) .isEqualTo("I know an old lady who swallowed a horse." + "\n" + "She's dead, of course!"); - } @Disabled("Remove to run test") @Test @DisplayName("multiple verses") public void multipleVerses() { - assertThat(foodChain.verses(1, 3)) .isEqualTo("I know an old lady who swallowed a fly." + "\n" @@ -200,14 +183,12 @@ public void multipleVerses() { + "She swallowed the spider to catch the fly." + "\n" + "I don't know why she swallowed the fly. Perhaps she'll die."); - } @Disabled("Remove to run test") @Test @DisplayName("full song") public void fullSong() { - assertThat(foodChain.verses(1, 8)) .isEqualTo("I know an old lady who swallowed a fly." + "\n" @@ -313,7 +294,6 @@ public void fullSong() { + "I know an old lady who swallowed a horse." + "\n" + "She's dead, of course!"); - } } diff --git a/exercises/practice/grains/src/test/java/GrainsTest.java b/exercises/practice/grains/src/test/java/GrainsTest.java index 5dde6d7fb..d81579ba3 100644 --- a/exercises/practice/grains/src/test/java/GrainsTest.java +++ b/exercises/practice/grains/src/test/java/GrainsTest.java @@ -20,113 +20,91 @@ public void setUp() { @Test @DisplayName("returns the number of grains on the square -> grains on square 1") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare1() { - assertThat(grains.grainsOnSquare(1)) .isEqualTo(new BigInteger("1")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 2") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare2() { - assertThat(grains.grainsOnSquare(2)) .isEqualTo(new BigInteger("2")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 3") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare3() { - assertThat(grains.grainsOnSquare(3)) .isEqualTo(new BigInteger("4")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 4") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare4() { - assertThat(grains.grainsOnSquare(4)) .isEqualTo(new BigInteger("8")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 16") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare16() { - assertThat(grains.grainsOnSquare(16)) .isEqualTo(new BigInteger("32768")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 32") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare32() { - assertThat(grains.grainsOnSquare(32)) .isEqualTo(new BigInteger("2147483648")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> grains on square 64") public void returnsTheNumberOfGrainsOnTheSquareGrainsOnSquare64() { - assertThat(grains.grainsOnSquare(64)) .isEqualTo(new BigInteger("9223372036854775808")); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> square 0 is invalid") public void returnsTheNumberOfGrainsOnTheSquareSquare0IsInvalid() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(0)) .withMessage("square must be between 1 and 64"); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> negative square is invalid") public void returnsTheNumberOfGrainsOnTheSquareNegativeSquareIsInvalid() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(-1)) .withMessage("square must be between 1 and 64"); - } @Disabled("Remove to run test") @Test @DisplayName("returns the number of grains on the square -> square greater than 64 is invalid") public void returnsTheNumberOfGrainsOnTheSquareSquareGreaterThan64IsInvalid() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> grains.grainsOnSquare(65)) .withMessage("square must be between 1 and 64"); - } @Disabled("Remove to run test") @Test @DisplayName("returns the total number of grains on the board") public void returnsTheTotalNumberOfGrainsOnTheBoard() { - assertThat(grains.grainsOnBoard()) .isEqualTo(new BigInteger("18446744073709551615")); - } } diff --git a/exercises/practice/hamming/src/test/java/HammingTest.java b/exercises/practice/hamming/src/test/java/HammingTest.java index ca0243b34..d6eaff62c 100644 --- a/exercises/practice/hamming/src/test/java/HammingTest.java +++ b/exercises/practice/hamming/src/test/java/HammingTest.java @@ -10,94 +10,76 @@ public class HammingTest { @Test @DisplayName("empty strands") public void emptyStrands() { - assertThat(new Hamming("", "").getHammingDistance()) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("single letter identical strands") public void singleLetterIdenticalStrands() { - assertThat(new Hamming("A", "A").getHammingDistance()) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("single letter different strands") public void singleLetterDifferentStrands() { - assertThat(new Hamming("G", "T").getHammingDistance()) .isEqualTo(1); - } @Disabled("Remove to run test") @Test @DisplayName("long identical strands") public void longIdenticalStrands() { - assertThat(new Hamming("GGACTGAAATCTG", "GGACTGAAATCTG").getHammingDistance()) .isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("long different strands") public void longDifferentStrands() { - assertThat(new Hamming("GGACGGATTCTG", "AGGACGGATTCT").getHammingDistance()) .isEqualTo(9); - } @Disabled("Remove to run test") @Test @DisplayName("disallow first strand longer") public void disallowFirstStrandLonger() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("AATG", "AAA")) .withMessage("strands must be of equal length"); - } @Disabled("Remove to run test") @Test @DisplayName("disallow second strand longer") public void disallowSecondStrandLonger() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("ATA", "AGTG")) .withMessage("strands must be of equal length"); - } @Disabled("Remove to run test") @Test @DisplayName("disallow empty first strand") public void disallowEmptyFirstStrand() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("", "G")) .withMessage("strands must be of equal length"); - } @Disabled("Remove to run test") @Test @DisplayName("disallow empty second strand") public void disallowEmptySecondStrand() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Hamming("G", "")) .withMessage("strands must be of equal length"); - } } diff --git a/exercises/practice/house/src/test/java/HouseTest.java b/exercises/practice/house/src/test/java/HouseTest.java index e56b4612a..fc904a6c2 100644 --- a/exercises/practice/house/src/test/java/HouseTest.java +++ b/exercises/practice/house/src/test/java/HouseTest.java @@ -17,124 +17,103 @@ public void setUp() { @Test @DisplayName("verse one - the house that jack built") public void verseOneTheHouseThatJackBuilt() { - assertThat(house.verse(1)) .isEqualTo("This is the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse two - the malt that lay") public void verseTwoTheMaltThatLay() { - assertThat(house.verse(2)) .isEqualTo("This is the malt that lay in the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse three - the rat that ate") public void verseThreeTheRatThatAte() { - assertThat(house.verse(3)) .isEqualTo("This is the rat that ate the malt that lay in the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse four - the cat that killed") public void verseFourTheCatThatKilled() { - assertThat(house.verse(4)) .isEqualTo("This is the cat that killed the rat that ate the malt that lay in the " + "house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse five - the dog that worried") public void verseFiveTheDogThatWorried() { - assertThat(house.verse(5)) .isEqualTo("This is the dog that worried the cat that killed the rat that ate the " + "malt that lay in the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse six - the cow with the crumpled horn") public void verseSixTheCowWithTheCrumpledHorn() { - assertThat(house.verse(6)) .isEqualTo("This is the cow with the crumpled horn that tossed the dog that " + "worried the cat that killed the rat that ate the malt that lay in the " + "house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse seven - the maiden all forlorn") public void verseSevenTheMaidenAllForlorn() { - assertThat(house.verse(7)) .isEqualTo("This is the maiden all forlorn that milked the cow with the crumpled " + "horn that tossed the dog that worried the cat that killed the rat that " + "ate the malt that lay in the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse eight - the man all tattered and torn") public void verseEightTheManAllTatteredAndTorn() { - assertThat(house.verse(8)) .isEqualTo("This is the man all tattered and torn that kissed the maiden all " + "forlorn that milked the cow with the crumpled horn that tossed the dog " + "that worried the cat that killed the rat that ate the malt that lay in " + "the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse nine - the priest all shaven and shorn") public void verseNineThePriestAllShavenAndShorn() { - assertThat(house.verse(9)) .isEqualTo("This is the priest all shaven and shorn that married the man all " + "tattered and torn that kissed the maiden all forlorn that milked the " + "cow with the crumpled horn that tossed the dog that worried the cat " + "that killed the rat that ate the malt that lay in the house that Jack " + "built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse 10 - the rooster that crowed in the morn") public void verse10TheRoosterThatCrowedInTheMorn() { - assertThat(house.verse(10)) .isEqualTo("This is the rooster that crowed in the morn that woke the priest all " + "shaven and shorn that married the man all tattered and torn that " + "kissed the maiden all forlorn that milked the cow with the crumpled " + "horn that tossed the dog that worried the cat that killed the rat that " + "ate the malt that lay in the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse 11 - the farmer sowing his corn") public void verse11TheFarmerSowingHisCorn() { - assertThat(house.verse(11)) .isEqualTo("This is the farmer sowing his corn that kept the rooster that crowed " + "in the morn that woke the priest all shaven and shorn that married the " @@ -142,14 +121,12 @@ public void verse11TheFarmerSowingHisCorn() { + "milked the cow with the crumpled horn that tossed the dog that worried " + "the cat that killed the rat that ate the malt that lay in the house " + "that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("verse 12 - the horse and the hound and the horn") public void verse12TheHorseAndTheHoundAndTheHorn() { - assertThat(house.verse(12)) .isEqualTo("This is the horse and the hound and the horn that belonged to the " + "farmer sowing his corn that kept the rooster that crowed in the morn " @@ -158,14 +135,12 @@ public void verse12TheHorseAndTheHoundAndTheHorn() { + "cow with the crumpled horn that tossed the dog that worried the cat " + "that killed the rat that ate the malt that lay in the house that Jack " + "built."); - } @Disabled("Remove to run test") @Test @DisplayName("multiple verses") public void multipleVerses() { - assertThat(house.verses(4, 8)) .isEqualTo("This is the cat that killed the rat that ate the malt that lay in the " + "house that Jack built." @@ -185,14 +160,12 @@ public void multipleVerses() { + "forlorn that milked the cow with the crumpled horn that tossed the dog " + "that worried the cat that killed the rat that ate the malt that lay in " + "the house that Jack built."); - } @Disabled("Remove to run test") @Test @DisplayName("full rhyme") public void fullRhyme() { - assertThat(house.sing()) .isEqualTo("This is the house that Jack built." + "\n" @@ -245,7 +218,6 @@ public void fullRhyme() { + "cow with the crumpled horn that tossed the dog that worried the cat " + "that killed the rat that ate the malt that lay in the house that Jack " + "built."); - } } diff --git a/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java b/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java index 755c17409..053fc25b3 100644 --- a/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java +++ b/exercises/practice/intergalactic-transmission/src/test/java/IntergalacticTransmissionTest.java @@ -12,115 +12,96 @@ public class IntergalacticTransmissionTest { @Test @DisplayName("calculate transmit sequences -> empty message") public void calculateTransmitSequencesEmptyMessage() { - List input = List.of(); List expected = List.of(); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0x00 is transmitted as 0x0000") public void calculateTransmitSequences0x00IsTransmittedAs0x0000() { - List input = List.of(0x00); List expected = List.of(0x00, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0x02 is transmitted as 0x0300") public void calculateTransmitSequences0x02IsTransmittedAs0x0300() { - List input = List.of(0x02); List expected = List.of(0x03, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0x06 is transmitted as 0x0600") public void calculateTransmitSequences0x06IsTransmittedAs0x0600() { - List input = List.of(0x06); List expected = List.of(0x06, 0x00); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0x05 is transmitted as 0x0581") public void calculateTransmitSequences0x05IsTransmittedAs0x0581() { - List input = List.of(0x05); List expected = List.of(0x05, 0x81); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0x29 is transmitted as 0x2881") public void calculateTransmitSequences0x29IsTransmittedAs0x2881() { - List input = List.of(0x29); List expected = List.of(0x28, 0x81); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> 0xc001c0de is transmitted as 0xc000711be1") public void calculateTransmitSequences0xc001c0deIsTransmittedAs0xc000711be1() { - List input = List.of(0xc0, 0x01, 0xc0, 0xde); List expected = List.of(0xc0, 0x00, 0x71, 0x1b, 0xe1); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> six byte message") public void calculateTransmitSequencesSixByteMessage() { - List input = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x21); List expected = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0x84); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> seven byte message") public void calculateTransmitSequencesSevenByteMessage() { - List input = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x31, 0x21); List expected = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x42); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> eight byte message") public void calculateTransmitSequencesEightByteMessage() { - List input = List.of(0xc0, 0x01, 0x13, 0x37, 0xc0, 0xde, 0x21, 0x21); List expected = List.of( 0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, @@ -128,14 +109,12 @@ public void calculateTransmitSequencesEightByteMessage() { ); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("calculate transmit sequences -> twenty byte message") public void calculateTransmitSequencesTwentyByteMessage() { - List input = List.of( 0x45, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x6d, 0x20, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, @@ -148,155 +127,129 @@ public void calculateTransmitSequencesTwentyByteMessage() { ); assertThat(IntergalacticTransmission.getTransmitSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> empty message") public void decodeReceivedMessagesEmptyMessage() { - List input = List.of(); List expected = List.of(); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> zero message") public void decodeReceivedMessagesZeroMessage() { - List input = List.of(0x00, 0x00); List expected = List.of(0x00); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> 0x0300 is decoded to 0x02") public void decodeReceivedMessages0x0300IsDecodedTo0x02() { - List input = List.of(0x03, 0x00); List expected = List.of(0x02); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> 0x0581 is decoded to 0x05") public void decodeReceivedMessages0x0581IsDecodedTo0x05() { - List input = List.of(0x05, 0x81); List expected = List.of(0x05); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> 0x2881 is decoded to 0x29") public void decodeReceivedMessages0x2881IsDecodedTo0x29() { - List input = List.of(0x28, 0x81); List expected = List.of(0x29); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> first byte has wrong parity") public void decodeReceivedMessagesFirstByteHasWrongParity() { - List input = List.of(0x07, 0x00); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> second byte has wrong parity") public void decodeReceivedMessagesSecondByteHasWrongParity() { - List input = List.of(0x03, 0x68); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> 0xcf4b00 is decoded to 0xce94") public void decodeReceivedMessages0xcf4b00IsDecodedTo0xce94() { - List input = List.of(0xcf, 0x4b, 0x00); List expected = List.of(0xce, 0x94); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> 0xe2566500 is decoded to 0xe2ad90") public void decodeReceivedMessages0xe2566500IsDecodedTo0xe2ad90() { - List input = List.of(0xe2, 0x56, 0x65, 0x00); List expected = List.of(0xe2, 0xad, 0x90); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> six byte message") public void decodeReceivedMessagesSixByteMessage() { - List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0x84); List expected = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> seven byte message") public void decodeReceivedMessagesSevenByteMessage() { - List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x42); List expected = List.of(0x47, 0x72, 0x65, 0x61, 0x74, 0x31, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> last byte has wrong parity") public void decodeReceivedMessagesLastByteHasWrongParity() { - List input = List.of(0x47, 0xb8, 0x99, 0xac, 0x17, 0xa0, 0xc5, 0x43); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> eight byte message") public void decodeReceivedMessagesEightByteMessage() { - List input = List.of( 0xc0, 0x00, 0x44, 0x66, 0x7d, 0x06, 0x78, 0x42, 0x21, 0x81 @@ -304,14 +257,12 @@ public void decodeReceivedMessagesEightByteMessage() { List expected = List.of(0xc0, 0x01, 0x13, 0x37, 0xc0, 0xde, 0x21, 0x21); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> twenty byte message") public void decodeReceivedMessagesTwentyByteMessage() { - List input = List.of( 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, 0x6c, 0x90, 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xee, @@ -324,14 +275,12 @@ public void decodeReceivedMessagesTwentyByteMessage() { ); assertThat(IntergalacticTransmission.decodeSequence(input)) .isEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("decode received messages -> wrong parity on 16th byte") public void decodeReceivedMessagesWrongParityOn16thByte() { - List input = List.of( 0x44, 0xbd, 0x18, 0xaf, 0x27, 0x1b, 0xa5, 0xe7, 0x6c, 0x90, 0x1b, 0x2e, 0x33, 0x03, 0x84, 0xef, @@ -339,7 +288,6 @@ public void decodeReceivedMessagesWrongParityOn16thByte() { ); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); - } } diff --git a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java index 078876f1f..20f8625eb 100644 --- a/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java +++ b/exercises/practice/killer-sudoku-helper/src/test/java/KillerSudokuHelperTest.java @@ -19,139 +19,116 @@ public void setUp() { @Test @DisplayName("Trivial 1-digit cages -> 1") public void trivial1DigitCages1() { - assertThat(helper.combinationsInCage( 1, 1)) .isEqualTo(List.of(List.of(1))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 2") public void trivial1DigitCages2() { - assertThat(helper.combinationsInCage( 2, 1)) .isEqualTo(List.of(List.of(2))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 3") public void trivial1DigitCages3() { - assertThat(helper.combinationsInCage( 3, 1)) .isEqualTo(List.of(List.of(3))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 4") public void trivial1DigitCages4() { - assertThat(helper.combinationsInCage( 4, 1)) .isEqualTo(List.of(List.of(4))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 5") public void trivial1DigitCages5() { - assertThat(helper.combinationsInCage( 5, 1)) .isEqualTo(List.of(List.of(5))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 6") public void trivial1DigitCages6() { - assertThat(helper.combinationsInCage( 6, 1)) .isEqualTo(List.of(List.of(6))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 7") public void trivial1DigitCages7() { - assertThat(helper.combinationsInCage( 7, 1)) .isEqualTo(List.of(List.of(7))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 8") public void trivial1DigitCages8() { - assertThat(helper.combinationsInCage( 8, 1)) .isEqualTo(List.of(List.of(8))); - } @Disabled("Remove to run test") @Test @DisplayName("Trivial 1-digit cages -> 9") public void trivial1DigitCages9() { - assertThat(helper.combinationsInCage( 9, 1)) .isEqualTo(List.of(List.of(9))); - } @Disabled("Remove to run test") @Test @DisplayName("Cage with sum 45 contains all digits 1:9") public void cageWithSum45ContainsAllDigits19() { - assertThat(helper.combinationsInCage( 45, 9)) .isEqualTo(List.of(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9))); - } @Disabled("Remove to run test") @Test @DisplayName("Cage with only 1 possible combination") public void cageWithOnly1PossibleCombination() { - assertThat(helper.combinationsInCage( 7, 3)) .isEqualTo(List.of(List.of(1, 2, 4))); - } @Disabled("Remove to run test") @Test @DisplayName("Cage with several combinations") public void cageWithSeveralCombinations() { - assertThat(helper.combinationsInCage( 10, 2)) @@ -161,20 +138,17 @@ public void cageWithSeveralCombinations() { List.of(3, 7), List.of(4, 6) )); - } @Disabled("Remove to run test") @Test @DisplayName("Cage with several combinations that is restricted") public void cageWithSeveralCombinationsThatIsRestricted() { - assertThat(helper.combinationsInCage( 10, 2, List.of(1, 4))) .isEqualTo(List.of(List.of(2, 8), List.of(3, 7))); - } } diff --git a/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java b/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java index 86618a193..2870a6e04 100644 --- a/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java +++ b/exercises/practice/largest-series-product/src/test/java/LargestSeriesProductCalculatorTest.java @@ -10,111 +10,91 @@ public class LargestSeriesProductCalculatorTest { @Test @DisplayName("finds the largest product if span equals length") public void findsTheLargestProductIfSpanEqualsLength() { - assertThat(new LargestSeriesProductCalculator("29") .calculateLargestProductForSeriesLength(2)) .isEqualTo(18L); - } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 2 with numbers in order") public void canFindTheLargestProductOf2WithNumbersInOrder() { - assertThat(new LargestSeriesProductCalculator("0123456789") .calculateLargestProductForSeriesLength(2)) .isEqualTo(72L); - } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 2") public void canFindTheLargestProductOf2() { - assertThat(new LargestSeriesProductCalculator("576802143") .calculateLargestProductForSeriesLength(2)) .isEqualTo(48L); - } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 3 with numbers in order") public void canFindTheLargestProductOf3WithNumbersInOrder() { - assertThat(new LargestSeriesProductCalculator("0123456789") .calculateLargestProductForSeriesLength(3)) .isEqualTo(504L); - } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 3") public void canFindTheLargestProductOf3() { - assertThat(new LargestSeriesProductCalculator("1027839564") .calculateLargestProductForSeriesLength(3)) .isEqualTo(270L); - } @Disabled("Remove to run test") @Test @DisplayName("can find the largest product of 5 with numbers in order") public void canFindTheLargestProductOf5WithNumbersInOrder() { - assertThat(new LargestSeriesProductCalculator("0123456789") .calculateLargestProductForSeriesLength(5)) .isEqualTo(15120L); - } @Disabled("Remove to run test") @Test @DisplayName("can get the largest product of a big number") public void canGetTheLargestProductOfABigNumber() { - assertThat(new LargestSeriesProductCalculator("73167176531330624919225119674426574742355349194934") .calculateLargestProductForSeriesLength(6)) .isEqualTo(23520L); - } @Disabled("Remove to run test") @Test @DisplayName("reports zero if the only digits are zero") public void reportsZeroIfTheOnlyDigitsAreZero() { - assertThat(new LargestSeriesProductCalculator("0000") .calculateLargestProductForSeriesLength(2)) .isEqualTo(0L); - } @Disabled("Remove to run test") @Test @DisplayName("reports zero if all spans include zero") public void reportsZeroIfAllSpansIncludeZero() { - assertThat(new LargestSeriesProductCalculator("99099") .calculateLargestProductForSeriesLength(3)) .isEqualTo(0L); - } @Disabled("Remove to run test") @Test @DisplayName("rejects invalid character in digits") public void rejectsInvalidCharacterInDigits() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new LargestSeriesProductCalculator("1234a5") .calculateLargestProductForSeriesLength(2)) .withMessage("String to search may only contain digits."); - } } diff --git a/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java b/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java index 3a8fc5dea..cb3bba131 100644 --- a/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java +++ b/exercises/practice/nucleotide-count/src/test/java/NucleotideCounterTest.java @@ -12,7 +12,6 @@ public class NucleotideCounterTest { @Test @DisplayName("empty strand") public void emptyStrand() { - NucleotideCounter counter = new NucleotideCounter( ""); @@ -20,14 +19,12 @@ public void emptyStrand() { .containsExactlyInAnyOrderEntriesOf( Map.of('A', 0, 'C', 0, 'G', 0, 'T', 0)); - } @Disabled("Remove to run test") @Test @DisplayName("can count one nucleotide in single-character input") public void canCountOneNucleotideInSingleCharacterInput() { - NucleotideCounter counter = new NucleotideCounter( "G"); @@ -35,14 +32,12 @@ public void canCountOneNucleotideInSingleCharacterInput() { .containsExactlyInAnyOrderEntriesOf( Map.of('A', 0, 'C', 0, 'G', 1, 'T', 0)); - } @Disabled("Remove to run test") @Test @DisplayName("strand with repeated nucleotide") public void strandWithRepeatedNucleotide() { - NucleotideCounter counter = new NucleotideCounter( "GGGGGGG"); @@ -50,14 +45,12 @@ public void strandWithRepeatedNucleotide() { .containsExactlyInAnyOrderEntriesOf( Map.of('A', 0, 'C', 0, 'G', 7, 'T', 0)); - } @Disabled("Remove to run test") @Test @DisplayName("strand with multiple nucleotides") public void strandWithMultipleNucleotides() { - NucleotideCounter counter = new NucleotideCounter( "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"); @@ -65,17 +58,14 @@ public void strandWithMultipleNucleotides() { .containsExactlyInAnyOrderEntriesOf( Map.of('A', 20, 'C', 12, 'G', 17, 'T', 21)); - } @Disabled("Remove to run test") @Test @DisplayName("strand with invalid nucleotides") public void strandWithInvalidNucleotides() { - assertThatThrownBy(() -> new NucleotideCounter("AGXXACT")) .isInstanceOf(IllegalArgumentException.class); - } } diff --git a/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java b/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java index 2d121ebdf..39ffb29d1 100644 --- a/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java +++ b/exercises/practice/phone-number/src/test/java/PhoneNumberTest.java @@ -10,193 +10,157 @@ public class PhoneNumberTest { @Test @DisplayName("cleans the number") public void cleansTheNumber() { - assertThat(new PhoneNumber("(223) 456-7890").getNumber()) .isEqualTo("2234567890"); - } @Disabled("Remove to run test") @Test @DisplayName("cleans numbers with dots") public void cleansNumbersWithDots() { - assertThat(new PhoneNumber("223.456.7890").getNumber()) .isEqualTo("2234567890"); - } @Disabled("Remove to run test") @Test @DisplayName("cleans numbers with multiple spaces") public void cleansNumbersWithMultipleSpaces() { - assertThat(new PhoneNumber("223 456 7890 ").getNumber()) .isEqualTo("2234567890"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid when 9 digits") public void invalidWhen9Digits() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("123456789")) .withMessage("must not be fewer than 10 digits"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid when 11 digits does not start with a 1") public void invalidWhen11DigitsDoesNotStartWithA1() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("22234567890")) .withMessage("11 digits must start with 1"); - } @Disabled("Remove to run test") @Test @DisplayName("valid when 11 digits and starting with 1") public void validWhen11DigitsAndStartingWith1() { - assertThat(new PhoneNumber("12234567890").getNumber()) .isEqualTo("2234567890"); - } @Disabled("Remove to run test") @Test @DisplayName("valid when 11 digits and starting with 1 even with punctuation") public void validWhen11DigitsAndStartingWith1EvenWithPunctuation() { - assertThat(new PhoneNumber("+1 (223) 456-7890").getNumber()) .isEqualTo("2234567890"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid when more than 11 digits") public void invalidWhenMoreThan11Digits() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("321234567890")) .withMessage("must not be greater than 11 digits"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid with letters") public void invalidWithLetters() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("523-abc-7890")) .withMessage("letters not permitted"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid with punctuations") public void invalidWithPunctuations() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("523-@:!-7890")) .withMessage("punctuations not permitted"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 0") public void invalidIfAreaCodeStartsWith0() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(023) 456-7890")) .withMessage("area code cannot start with zero"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 1") public void invalidIfAreaCodeStartsWith1() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(123) 456-7890")) .withMessage("area code cannot start with one"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 0") public void invalidIfExchangeCodeStartsWith0() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(223) 056-7890")) .withMessage("exchange code cannot start with zero"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 1") public void invalidIfExchangeCodeStartsWith1() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("(223) 156-7890")) .withMessage("exchange code cannot start with one"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 0 on valid 11-digit number") public void invalidIfAreaCodeStartsWith0OnValid11DigitNumber() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (023) 456-7890")) .withMessage("area code cannot start with zero"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if area code starts with 1 on valid 11-digit number") public void invalidIfAreaCodeStartsWith1OnValid11DigitNumber() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (123) 456-7890")) .withMessage("area code cannot start with one"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 0 on valid 11-digit number") public void invalidIfExchangeCodeStartsWith0OnValid11DigitNumber() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (223) 056-7890")) .withMessage("exchange code cannot start with zero"); - } @Disabled("Remove to run test") @Test @DisplayName("invalid if exchange code starts with 1 on valid 11-digit number") public void invalidIfExchangeCodeStartsWith1OnValid11DigitNumber() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PhoneNumber("1 (223) 156-7890")) .withMessage("exchange code cannot start with one"); - } } diff --git a/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java index 5024b1430..3c2003b5e 100644 --- a/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java +++ b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java @@ -29,7 +29,6 @@ private void assertJigsawInfoEquals(JigsawInfo actual, JigsawInfo expected) { @Test @DisplayName("1000 pieces puzzle with 1.6 aspect ratio") public void test1000PiecesPuzzleWith16AspectRatio() { - JigsawInfo input = new JigsawInfo.Builder() .pieces(1000) .aspectRatio(1.6) @@ -45,14 +44,12 @@ public void test1000PiecesPuzzleWith16AspectRatio() { .build(); JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); - } @Disabled("Remove to run test") @Test @DisplayName("square puzzle with 32 rows") public void squarePuzzleWith32Rows() { - JigsawInfo input = new JigsawInfo.Builder() .rows(32) .format("square") @@ -68,14 +65,12 @@ public void squarePuzzleWith32Rows() { .build(); JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); - } @Disabled("Remove to run test") @Test @DisplayName("400 pieces square puzzle with only inside pieces and aspect ratio") public void test400PiecesSquarePuzzleWithOnlyInsidePiecesAndAspectRatio() { - JigsawInfo input = new JigsawInfo.Builder() .inside(324) .aspectRatio(1.0) @@ -91,14 +86,12 @@ public void test400PiecesSquarePuzzleWithOnlyInsidePiecesAndAspectRatio() { .build(); JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); - } @Disabled("Remove to run test") @Test @DisplayName("1500 pieces landscape puzzle with 30 rows and 5:3 aspect ratio") public void test1500PiecesLandscapePuzzleWith30RowsAnd53AspectRatio() { - JigsawInfo input = new JigsawInfo.Builder() .rows(30) .aspectRatio(1.6666666666666667) @@ -114,14 +107,12 @@ public void test1500PiecesLandscapePuzzleWith30RowsAnd53AspectRatio() { .build(); JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); - } @Disabled("Remove to run test") @Test @DisplayName("300 pieces portrait puzzle with 70 border pieces") public void test300PiecesPortraitPuzzleWith70BorderPieces() { - JigsawInfo input = new JigsawInfo.Builder() .pieces(300) .border(70) @@ -138,14 +129,12 @@ public void test300PiecesPortraitPuzzleWith70BorderPieces() { .build(); JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); assertJigsawInfoEquals(actual, expected); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with insufficient data") public void puzzleWithInsufficientData() { - JigsawInfo input = new JigsawInfo.Builder() .pieces(1500) .format("landscape") @@ -153,14 +142,12 @@ public void puzzleWithInsufficientData() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) .withMessage("Insufficient data"); - } @Disabled("Remove to run test") @Test @DisplayName("puzzle with contradictory data") public void puzzleWithContradictoryData() { - JigsawInfo input = new JigsawInfo.Builder() .rows(100) .columns(1000) @@ -169,7 +156,6 @@ public void puzzleWithContradictoryData() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) .withMessage("Contradictory data"); - } } diff --git a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java index 5be4e528e..7f2ab0c82 100644 --- a/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java +++ b/exercises/practice/protein-translation/src/test/java/ProteinTranslatorTest.java @@ -20,313 +20,251 @@ public void setUp() { @Test @DisplayName("Empty RNA sequence results in no proteins") public void emptyRnaSequenceResultsInNoProteins() { - assertThat(proteinTranslator.translate("")) .isEqualTo(List.of()); - } @Disabled("Remove to run test") @Test @DisplayName("Methionine RNA sequence") public void methionineRnaSequence() { - assertThat(proteinTranslator.translate("AUG")) .isEqualTo(List.of("Methionine")); - } @Disabled("Remove to run test") @Test @DisplayName("Phenylalanine RNA sequence 1") public void phenylalanineRnaSequence1() { - assertThat(proteinTranslator.translate("UUU")) .isEqualTo(List.of("Phenylalanine")); - } @Disabled("Remove to run test") @Test @DisplayName("Phenylalanine RNA sequence 2") public void phenylalanineRnaSequence2() { - assertThat(proteinTranslator.translate("UUC")) .isEqualTo(List.of("Phenylalanine")); - } @Disabled("Remove to run test") @Test @DisplayName("Leucine RNA sequence 1") public void leucineRnaSequence1() { - assertThat(proteinTranslator.translate("UUA")) .isEqualTo(List.of("Leucine")); - } @Disabled("Remove to run test") @Test @DisplayName("Leucine RNA sequence 2") public void leucineRnaSequence2() { - assertThat(proteinTranslator.translate("UUG")) .isEqualTo(List.of("Leucine")); - } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 1") public void serineRnaSequence1() { - assertThat(proteinTranslator.translate("UCU")) .isEqualTo(List.of("Serine")); - } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 2") public void serineRnaSequence2() { - assertThat(proteinTranslator.translate("UCC")) .isEqualTo(List.of("Serine")); - } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 3") public void serineRnaSequence3() { - assertThat(proteinTranslator.translate("UCA")) .isEqualTo(List.of("Serine")); - } @Disabled("Remove to run test") @Test @DisplayName("Serine RNA sequence 4") public void serineRnaSequence4() { - assertThat(proteinTranslator.translate("UCG")) .isEqualTo(List.of("Serine")); - } @Disabled("Remove to run test") @Test @DisplayName("Tyrosine RNA sequence 1") public void tyrosineRnaSequence1() { - assertThat(proteinTranslator.translate("UAU")) .isEqualTo(List.of("Tyrosine")); - } @Disabled("Remove to run test") @Test @DisplayName("Tyrosine RNA sequence 2") public void tyrosineRnaSequence2() { - assertThat(proteinTranslator.translate("UAC")) .isEqualTo(List.of("Tyrosine")); - } @Disabled("Remove to run test") @Test @DisplayName("Cysteine RNA sequence 1") public void cysteineRnaSequence1() { - assertThat(proteinTranslator.translate("UGU")) .isEqualTo(List.of("Cysteine")); - } @Disabled("Remove to run test") @Test @DisplayName("Cysteine RNA sequence 2") public void cysteineRnaSequence2() { - assertThat(proteinTranslator.translate("UGC")) .isEqualTo(List.of("Cysteine")); - } @Disabled("Remove to run test") @Test @DisplayName("Tryptophan RNA sequence") public void tryptophanRnaSequence() { - assertThat(proteinTranslator.translate("UGG")) .isEqualTo(List.of("Tryptophan")); - } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 1") public void stopCodonRnaSequence1() { - assertThat(proteinTranslator.translate("UAA")) .isEqualTo(List.of()); - } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 2") public void stopCodonRnaSequence2() { - assertThat(proteinTranslator.translate("UAG")) .isEqualTo(List.of()); - } @Disabled("Remove to run test") @Test @DisplayName("STOP codon RNA sequence 3") public void stopCodonRnaSequence3() { - assertThat(proteinTranslator.translate("UGA")) .isEqualTo(List.of()); - } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two protein codons translates into proteins") public void sequenceOfTwoProteinCodonsTranslatesIntoProteins() { - assertThat(proteinTranslator.translate("UUUUUU")) .isEqualTo(List.of("Phenylalanine", "Phenylalanine")); - } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two different protein codons translates into proteins") public void sequenceOfTwoDifferentProteinCodonsTranslatesIntoProteins() { - assertThat(proteinTranslator.translate("UUAUUG")) .isEqualTo(List.of("Leucine", "Leucine")); - } @Disabled("Remove to run test") @Test @DisplayName("Translate RNA strand into correct protein list") public void translateRnaStrandIntoCorrectProteinList() { - assertThat(proteinTranslator.translate("AUGUUUUGG")) .isEqualTo(List.of("Methionine", "Phenylalanine", "Tryptophan")); - } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at beginning of sequence") public void translationStopsIfStopCodonAtBeginningOfSequence() { - assertThat(proteinTranslator.translate("UAGUGG")) .isEqualTo(List.of()); - } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at end of two-codon sequence") public void translationStopsIfStopCodonAtEndOfTwoCodonSequence() { - assertThat(proteinTranslator.translate("UGGUAG")) .isEqualTo(List.of("Tryptophan")); - } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon at end of three-codon sequence") public void translationStopsIfStopCodonAtEndOfThreeCodonSequence() { - assertThat(proteinTranslator.translate("AUGUUUUAA")) .isEqualTo(List.of("Methionine", "Phenylalanine")); - } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon in middle of three-codon sequence") public void translationStopsIfStopCodonInMiddleOfThreeCodonSequence() { - assertThat(proteinTranslator.translate("UGGUAGUGG")) .isEqualTo(List.of("Tryptophan")); - } @Disabled("Remove to run test") @Test @DisplayName("Translation stops if STOP codon in middle of six-codon sequence") public void translationStopsIfStopCodonInMiddleOfSixCodonSequence() { - assertThat(proteinTranslator.translate("UGGUGUUAUUAAUGGUUU")) .isEqualTo(List.of("Tryptophan", "Cysteine", "Tyrosine")); - } @Disabled("Remove to run test") @Test @DisplayName("Sequence of two non-STOP codons does not translate to a STOP codon") public void sequenceOfTwoNonStopCodonsDoesNotTranslateToAStopCodon() { - assertThat(proteinTranslator.translate("AUGAUG")) .isEqualTo(List.of("Methionine", "Methionine")); - } @Disabled("Remove to run test") @Test @DisplayName("Non-existing codon can't translate") public void nonExistingCodonCanTTranslate() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("AAA")) .withMessage("Invalid codon"); - } @Disabled("Remove to run test") @Test @DisplayName("Unknown amino acids, not part of a codon, can't translate") public void unknownAminoAcidsNotPartOfACodonCanTTranslate() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("XYZ")) .withMessage("Invalid codon"); - } @Disabled("Remove to run test") @Test @DisplayName("Incomplete RNA sequence can't translate") public void incompleteRnaSequenceCanTTranslate() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> proteinTranslator.translate("AUGU")) .withMessage("Invalid codon"); - } @Disabled("Remove to run test") @Test @DisplayName("Incomplete RNA sequence can translate if valid until a STOP codon") public void incompleteRnaSequenceCanTranslateIfValidUntilAStopCodon() { - assertThat(proteinTranslator.translate("UUCUUCUAAUGGU")) .isEqualTo(List.of("Phenylalanine", "Phenylalanine")); - } } diff --git a/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java b/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java index d028624f2..c40babb60 100644 --- a/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java +++ b/exercises/practice/queen-attack/src/test/java/QueenAttackCalculatorTest.java @@ -11,9 +11,7 @@ public class QueenAttackCalculatorTest { @DisplayName("Test creation of Queens with valid and invalid positions -> queen with " + "a valid position") public void testCreationOfQueensWithValidAndInvalidPositionsQueenWithAValidPo() { - new Queen(2, 2); - } @Disabled("Remove to run test") @@ -21,10 +19,8 @@ public void testCreationOfQueensWithValidAndInvalidPositionsQueenWithAValidPo() @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + "have positive row") public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Queen(-2, 2)); - } @Disabled("Remove to run test") @@ -32,10 +28,8 @@ public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi() @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + "have row on board") public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHaveRowO() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Queen(8, 4)); - } @Disabled("Remove to run test") @@ -43,10 +37,8 @@ public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHaveRowO() @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + "have positive column") public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi2() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Queen(2, -2)); - } @Disabled("Remove to run test") @@ -54,108 +46,92 @@ public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHavePosi2() @DisplayName("Test creation of Queens with valid and invalid positions -> queen must " + "have column on board") public void testCreationOfQueensWithValidAndInvalidPositionsQueenMustHaveColu() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new Queen(4, 8)); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> cannot attack") public void testTheAbilityOfOneQueenToAttackAnotherCannotAttack() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(2, 4), new Queen(6, 6) ); assertThat(calculator.canQueensAttackOneAnother()).isFalse(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on same row") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSameRow() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(2, 4), new Queen(2, 6) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on same column") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSameColumn() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(4, 5), new Queen(2, 5) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on first diagonal") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnFirstDiagonal() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(2, 2), new Queen(0, 4) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on second diagonal") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnSecondDiagonal() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(2, 2), new Queen(3, 1) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on third diagonal") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnThirdDiagonal() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(2, 2), new Queen(1, 1) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @Test @DisplayName("Test the ability of one queen to attack another -> can attack on fourth diagonal") public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnFourthDiagonal() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(1, 7), new Queen(0, 6) ); assertThat(calculator.canQueensAttackOneAnother()).isTrue(); - } @Disabled("Remove to run test") @@ -164,14 +140,12 @@ public void testTheAbilityOfOneQueenToAttackAnotherCanAttackOnFourthDiagonal() { + "falling diagonals are only the same when reflected across the longest " + "falling diagonal") public void testTheAbilityOfOneQueenToAttackAnotherCannotAttackIfFallingDiago() { - QueenAttackCalculator calculator = new QueenAttackCalculator( new Queen(4, 1), new Queen(2, 5) ); assertThat(calculator.canQueensAttackOneAnother()).isFalse(); - } } diff --git a/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java b/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java index a22029a9d..0888ae5ea 100644 --- a/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java +++ b/exercises/practice/relative-distance/src/test/java/RelativeDistanceTest.java @@ -18,7 +18,6 @@ public void directParentChildRelation() { assertThat(rd.degreeOfSeparation("Vera", "Tomoko")) .isEqualTo(1); - } @Disabled("Remove to run test") @@ -31,7 +30,6 @@ public void siblingRelationship() { assertThat(rd.degreeOfSeparation("Olga", "Yassin")) .isEqualTo(1); - } @Disabled("Remove to run test") @@ -44,7 +42,6 @@ public void twoDegreesOfSeparationGrandchild() { assertThat(rd.degreeOfSeparation("Khadija", "Rami")) .isEqualTo(2); - } @Disabled("Remove to run test") @@ -57,7 +54,6 @@ public void unrelatedIndividuals() { assertThat(rd.degreeOfSeparation("Priya", "Kaito")) .isEqualTo(-1); - } @Disabled("Remove to run test") @@ -123,7 +119,6 @@ public void complexGraphCousins() { assertThat(rd.degreeOfSeparation("Dimitri", "Fabio")) .isEqualTo(9); - } @Disabled("Remove to run test") @@ -189,7 +184,6 @@ public void complexGraphNoShortcutFarRemovedNephew() { assertThat(rd.degreeOfSeparation("Lucia", "Jun")) .isEqualTo(14); - } @Disabled("Remove to run test") @@ -255,7 +249,6 @@ public void complexGraphSomeShortcutsCrossDownAndCrossUpCousinsSeveralTimesRe() assertThat(rd.degreeOfSeparation("Wyatt", "Xia")) .isEqualTo(12); - } } diff --git a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java index a084d1dc3..96e5f6949 100644 --- a/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java +++ b/exercises/practice/run-length-encoding/src/test/java/RunLengthEncodingTest.java @@ -17,130 +17,104 @@ public void setUp() { @Test @DisplayName("run-length encode a string -> empty string") public void runLengthEncodeAStringEmptyString() { - assertThat(runLengthEncoding.encode("")) .isEqualTo(""); - } @Disabled("Remove to run test") @Test @DisplayName("run-length encode a string -> single characters only are encoded without count") public void runLengthEncodeAStringSingleCharactersOnlyAreEncodedWithoutCount() { - assertThat(runLengthEncoding.encode("XYZ")) .isEqualTo("XYZ"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length encode a string -> string with no single characters") public void runLengthEncodeAStringStringWithNoSingleCharacters() { - assertThat(runLengthEncoding.encode("AABBBCCCC")) .isEqualTo("2A3B4C"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length encode a string -> single characters mixed with repeated characters") public void runLengthEncodeAStringSingleCharactersMixedWithRepeatedCharacters() { - assertThat(runLengthEncoding.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")) .isEqualTo("12WB12W3B24WB"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length encode a string -> multiple whitespace mixed in string") public void runLengthEncodeAStringMultipleWhitespaceMixedInString() { - assertThat(runLengthEncoding.encode(" hsqq qww ")) .isEqualTo("2 hs2q q2w2 "); - } @Disabled("Remove to run test") @Test @DisplayName("run-length encode a string -> lowercase characters") public void runLengthEncodeAStringLowercaseCharacters() { - assertThat(runLengthEncoding.encode("aabbbcccc")) .isEqualTo("2a3b4c"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> empty string") public void runLengthDecodeAStringEmptyString() { - assertThat(runLengthEncoding.decode("")) .isEqualTo(""); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> single characters only") public void runLengthDecodeAStringSingleCharactersOnly() { - assertThat(runLengthEncoding.decode("XYZ")) .isEqualTo("XYZ"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> string with no single characters") public void runLengthDecodeAStringStringWithNoSingleCharacters() { - assertThat(runLengthEncoding.decode("2A3B4C")) .isEqualTo("AABBBCCCC"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> single characters with repeated characters") public void runLengthDecodeAStringSingleCharactersWithRepeatedCharacters() { - assertThat(runLengthEncoding.decode("12WB12W3B24WB")) .isEqualTo("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> multiple whitespace mixed in string") public void runLengthDecodeAStringMultipleWhitespaceMixedInString() { - assertThat(runLengthEncoding.decode("2 hs2q q2w2 ")) .isEqualTo(" hsqq qww "); - } @Disabled("Remove to run test") @Test @DisplayName("run-length decode a string -> lowercase string") public void runLengthDecodeAStringLowercaseString() { - assertThat(runLengthEncoding.decode("2a3b4c")) .isEqualTo("aabbbcccc"); - } @Disabled("Remove to run test") @Test @DisplayName("encode and then decode -> encode followed by decode gives original string") public void encodeAndThenDecodeEncodeFollowedByDecodeGivesOriginalString() { - assertThat(runLengthEncoding.decode(runLengthEncoding.encode("zzz ZZ zZ"))) .isEqualTo("zzz ZZ zZ"); - } } diff --git a/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java b/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java index 11d5e435f..d77272c76 100644 --- a/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java +++ b/exercises/practice/spiral-matrix/src/test/java/SpiralMatrixBuilderTest.java @@ -17,46 +17,37 @@ public void setUp() { @Test @DisplayName("empty spiral") public void emptySpiral() { - assertThat(spiralMatrixBuilder.buildMatrixOfSize(0)).isEmpty(); - } @Disabled("Remove to run test") @Test @DisplayName("trivial spiral") public void trivialSpiral() { - int[][] expected = new int[][]{{1}}; assertThat(spiralMatrixBuilder.buildMatrixOfSize(1)).isDeepEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 2") public void spiralOfSize2() { - int[][] expected = new int[][]{{1, 2}, {4, 3}}; assertThat(spiralMatrixBuilder.buildMatrixOfSize(2)).isDeepEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 3") public void spiralOfSize3() { - int[][] expected = new int[][]{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; assertThat(spiralMatrixBuilder.buildMatrixOfSize(3)).isDeepEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 4") public void spiralOfSize4() { - int[][] expected = new int[][]{ {1, 2, 3, 4}, {12, 13, 14, 5}, @@ -64,14 +55,12 @@ public void spiralOfSize4() { {10, 9, 8, 7} }; assertThat(spiralMatrixBuilder.buildMatrixOfSize(4)).isDeepEqualTo(expected); - } @Disabled("Remove to run test") @Test @DisplayName("spiral of size 5") public void spiralOfSize5() { - int[][] expected = new int[][]{ {1, 2, 3, 4, 5}, {16, 17, 18, 19, 6}, @@ -80,7 +69,6 @@ public void spiralOfSize5() { {13, 12, 11, 10, 9} }; assertThat(spiralMatrixBuilder.buildMatrixOfSize(5)).isDeepEqualTo(expected); - } } diff --git a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java index a52320570..6ed6160c9 100644 --- a/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java +++ b/exercises/practice/state-of-tic-tac-toe/src/test/java/StateOfTicTacToeTest.java @@ -18,274 +18,220 @@ public void setUp() { @Test @DisplayName("Won games -> Finished game where X won via left column victory") public void wonGamesFinishedGameWhereXWonViaLeftColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOO", "X ", "X "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via middle column victory") public void wonGamesFinishedGameWhereXWonViaMiddleColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"OXO", " X ", " X "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via right column victory") public void wonGamesFinishedGameWhereXWonViaRightColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"OOX", " X", " X"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via left column victory") public void wonGamesFinishedGameWhereOWonViaLeftColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"OXX", "OX ", "O "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via middle column victory") public void wonGamesFinishedGameWhereOWonViaMiddleColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", " OX", " O "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via right column victory") public void wonGamesFinishedGameWhereOWonViaRightColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XXO", " XO", " O"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via top row victory") public void wonGamesFinishedGameWhereXWonViaTopRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "O "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via middle row victory") public void wonGamesFinishedGameWhereXWonViaMiddleRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"O ", "XXX", " O "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via bottom row victory") public void wonGamesFinishedGameWhereXWonViaBottomRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{" OO", "O X", "XXX"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via top row victory") public void wonGamesFinishedGameWhereOWonViaTopRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"OOO", "XXO", "XX "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via middle row victory") public void wonGamesFinishedGameWhereOWonViaMiddleRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XX ", "OOO", "X "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via bottom row victory") public void wonGamesFinishedGameWhereOWonViaBottomRowVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", " XX", "OOO"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via falling diagonal victory") public void wonGamesFinishedGameWhereXWonViaFallingDiagonalVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOO", " X ", " X"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via rising diagonal victory") public void wonGamesFinishedGameWhereXWonViaRisingDiagonalVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"O X", "OX ", "X "})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via falling diagonal victory") public void wonGamesFinishedGameWhereOWonViaFallingDiagonalVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"OXX", "OOX", "X O"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where O won via rising diagonal victory") public void wonGamesFinishedGameWhereOWonViaRisingDiagonalVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{" O", " OX", "OXX"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via a row and a column victory") public void wonGamesFinishedGameWhereXWonViaARowAndAColumnVictory() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XXX", "XOO", "XOO"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Won games -> Finished game where X won via two diagonal victories") public void wonGamesFinishedGameWhereXWonViaTwoDiagonalVictories() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", "OXO", "XOX"})) .isEqualTo(GameState.WIN); - } @Disabled("Remove to run test") @Test @DisplayName("Drawn games -> Draw") public void drawnGamesDraw() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XOX", "XXO", "OXO"})) .isEqualTo(GameState.DRAW); - } @Disabled("Remove to run test") @Test @DisplayName("Drawn games -> Another draw") public void drawnGamesAnotherDraw() { - assertThat(stateOfTicTacToe.determineState(new String[]{"XXO", "OXX", "XOO"})) .isEqualTo(GameState.DRAW); - } @Disabled("Remove to run test") @Test @DisplayName("Ongoing games -> Ongoing game: one move in") public void ongoingGamesOngoingGameOneMoveIn() { - assertThat(stateOfTicTacToe.determineState(new String[]{" ", "X ", " "})) .isEqualTo(GameState.ONGOING); - } @Disabled("Remove to run test") @Test @DisplayName("Ongoing games -> Ongoing game: two moves in") public void ongoingGamesOngoingGameTwoMovesIn() { - assertThat(stateOfTicTacToe.determineState(new String[]{"O ", " X ", " "})) .isEqualTo(GameState.ONGOING); - } @Disabled("Remove to run test") @Test @DisplayName("Ongoing games -> Ongoing game: five moves in") public void ongoingGamesOngoingGameFiveMovesIn() { - assertThat(stateOfTicTacToe.determineState(new String[]{"X ", " XO", "OX "})) .isEqualTo(GameState.ONGOING); - } @Disabled("Remove to run test") @Test @DisplayName("Invalid boards -> Invalid board: X went twice") public void invalidBoardsInvalidBoardXWentTwice() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XX ", " ", " "})) .withMessage("Wrong turn order: X went twice"); - } @Disabled("Remove to run test") @Test @DisplayName("Invalid boards -> Invalid board: O started") public void invalidBoardsInvalidBoardOStarted() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"OOX", " ", " "})) .withMessage("Wrong turn order: O started"); - } @Disabled("Remove to run test") @Test @DisplayName("Invalid boards -> Invalid board: X won and O kept playing") public void invalidBoardsInvalidBoardXWonAndOKeptPlaying() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", " "})) .withMessage("Impossible board: game should have ended after the game was won"); - } @Disabled("Remove to run test") @Test @DisplayName("Invalid boards -> Invalid board: players kept playing after a win") public void invalidBoardsInvalidBoardPlayersKeptPlayingAfterAWin() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> stateOfTicTacToe.determineState(new String[]{"XXX", "OOO", "XOX"})) .withMessage("Impossible board: game should have ended after the game was won"); - } } diff --git a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java index 76637c618..583b9c65d 100644 --- a/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java +++ b/exercises/practice/twelve-days/src/test/java/TwelveDaysTest.java @@ -17,157 +17,132 @@ public void setUp() { @Test @DisplayName("verse -> first day a partridge in a pear tree") public void verseFirstDayAPartridgeInAPearTree() { - assertThat(twelveDays.verse(1)) .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + "a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> second day two turtle doves") public void verseSecondDayTwoTurtleDoves() { - assertThat(twelveDays.verse(2)) .isEqualTo("On the second day of Christmas my true love gave to me: two Turtle " + "Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> third day three french hens") public void verseThirdDayThreeFrenchHens() { - assertThat(twelveDays.verse(3)) .isEqualTo("On the third day of Christmas my true love gave to me: three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> fourth day four calling birds") public void verseFourthDayFourCallingBirds() { - assertThat(twelveDays.verse(4)) .isEqualTo("On the fourth day of Christmas my true love gave to me: four Calling " + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + "Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> fifth day five gold rings") public void verseFifthDayFiveGoldRings() { - assertThat(twelveDays.verse(5)) .isEqualTo("On the fifth day of Christmas my true love gave to me: five Gold " + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + "Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> sixth day six geese-a-laying") public void verseSixthDaySixGeeseALaying() { - assertThat(twelveDays.verse(6)) .isEqualTo("On the sixth day of Christmas my true love gave to me: six " + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> seventh day seven swans-a-swimming") public void verseSeventhDaySevenSwansASwimming() { - assertThat(twelveDays.verse(7)) .isEqualTo("On the seventh day of Christmas my true love gave to me: seven " + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + "Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> eighth day eight maids-a-milking") public void verseEighthDayEightMaidsAMilking() { - assertThat(twelveDays.verse(8)) .isEqualTo("On the eighth day of Christmas my true love gave to me: eight " + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + "Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> ninth day nine ladies dancing") public void verseNinthDayNineLadiesDancing() { - assertThat(twelveDays.verse(9)) .isEqualTo("On the ninth day of Christmas my true love gave to me: nine Ladies " + "Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> tenth day ten lords-a-leaping") public void verseTenthDayTenLordsALeaping() { - assertThat(twelveDays.verse(10)) .isEqualTo("On the tenth day of Christmas my true love gave to me: ten " + "Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven " + "Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling " + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " + "Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> eleventh day eleven pipers piping") public void verseEleventhDayElevenPipersPiping() { - assertThat(twelveDays.verse(11)) .isEqualTo("On the eleventh day of Christmas my true love gave to me: eleven " + "Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight " + "Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold " + "Rings, four Calling Birds, three French Hens, two Turtle Doves, and a " + "Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("verse -> twelfth day twelve drummers drumming") public void verseTwelfthDayTwelveDrummersDrumming() { - assertThat(twelveDays.verse(12)) .isEqualTo("On the twelfth day of Christmas my true love gave to me: twelve " + "Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine " + "Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("lyrics -> recites first three verses of the song") public void lyricsRecitesFirstThreeVersesOfTheSong() { - assertThat(twelveDays.verses(1, 3)) .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + "a Pear Tree.\n" @@ -177,14 +152,12 @@ public void lyricsRecitesFirstThreeVersesOfTheSong() { + "\n" + "On the third day of Christmas my true love gave to me: three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("lyrics -> recites three verses from the middle of the song") public void lyricsRecitesThreeVersesFromTheMiddleOfTheSong() { - assertThat(twelveDays.verses(4, 6)) .isEqualTo("On the fourth day of Christmas my true love gave to me: four Calling " + "Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear " @@ -197,14 +170,12 @@ public void lyricsRecitesThreeVersesFromTheMiddleOfTheSong() { + "On the sixth day of Christmas my true love gave to me: six " + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } @Disabled("Remove to run test") @Test @DisplayName("lyrics -> recites the whole song") public void lyricsRecitesTheWholeSong() { - assertThat(twelveDays.sing()) .isEqualTo("On the first day of Christmas my true love gave to me: a Partridge in " + "a Pear Tree.\n" @@ -259,7 +230,6 @@ public void lyricsRecitesTheWholeSong() { + "Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six " + "Geese-a-Laying, five Gold Rings, four Calling Birds, three French " + "Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"); - } } diff --git a/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java b/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java index 29c144bd7..d719be969 100644 --- a/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java +++ b/exercises/practice/two-bucket/src/test/java/TwoBucketTest.java @@ -10,7 +10,6 @@ public class TwoBucketTest { @Test @DisplayName("Measure using bucket one of size 3 and bucket two of size 5 - start with bucket one") public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketOne() { - Result bucketResult = new TwoBucket( 3, 5, @@ -21,14 +20,12 @@ public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketOne() assertThat(bucketResult.getTotalMoves()).isEqualTo(4); assertThat(bucketResult.getFinalBucket()).isEqualTo("one"); assertThat(bucketResult.getOtherBucket()).isEqualTo(5); - } @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 3 and bucket two of size 5 - start with bucket two") public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketTwo() { - Result bucketResult = new TwoBucket( 3, 5, @@ -39,14 +36,12 @@ public void measureUsingBucketOneOfSize3AndBucketTwoOfSize5StartWithBucketTwo() assertThat(bucketResult.getTotalMoves()).isEqualTo(8); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); assertThat(bucketResult.getOtherBucket()).isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 7 and bucket two of size 11 - start with bucket one") public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketOn() { - Result bucketResult = new TwoBucket( 7, 11, @@ -57,14 +52,12 @@ public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketOn() assertThat(bucketResult.getTotalMoves()).isEqualTo(14); assertThat(bucketResult.getFinalBucket()).isEqualTo("one"); assertThat(bucketResult.getOtherBucket()).isEqualTo(11); - } @Disabled("Remove to run test") @Test @DisplayName("Measure using bucket one of size 7 and bucket two of size 11 - start with bucket two") public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketTw() { - Result bucketResult = new TwoBucket( 7, 11, @@ -75,7 +68,6 @@ public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketTw() assertThat(bucketResult.getTotalMoves()).isEqualTo(18); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); assertThat(bucketResult.getOtherBucket()).isEqualTo(7); - } @Disabled("Remove to run test") @@ -83,7 +75,6 @@ public void measureUsingBucketOneOfSize7AndBucketTwoOfSize11StartWithBucketTw() @DisplayName("Measure one step using bucket one of size 1 and bucket two of size 3 - " + "start with bucket two") public void measureOneStepUsingBucketOneOfSize1AndBucketTwoOfSize3StartWithBu() { - Result bucketResult = new TwoBucket( 1, 3, @@ -94,7 +85,6 @@ public void measureOneStepUsingBucketOneOfSize1AndBucketTwoOfSize3StartWithBu() assertThat(bucketResult.getTotalMoves()).isEqualTo(1); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); assertThat(bucketResult.getOtherBucket()).isEqualTo(0); - } @Disabled("Remove to run test") @@ -102,7 +92,6 @@ public void measureOneStepUsingBucketOneOfSize1AndBucketTwoOfSize3StartWithBu() @DisplayName("Measure using bucket one of size 2 and bucket two of size 3 - start " + "with bucket one and end with bucket two") public void measureUsingBucketOneOfSize2AndBucketTwoOfSize3StartWithBucketOne() { - Result bucketResult = new TwoBucket( 2, 3, @@ -113,14 +102,12 @@ public void measureUsingBucketOneOfSize2AndBucketTwoOfSize3StartWithBucketOne() assertThat(bucketResult.getTotalMoves()).isEqualTo(2); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); assertThat(bucketResult.getOtherBucket()).isEqualTo(2); - } @Disabled("Remove to run test") @Test @DisplayName("Not possible to reach the goal") public void notPossibleToReachTheGoal() { - assertThatExceptionOfType(UnreachableGoalException.class) .isThrownBy(() -> new TwoBucket( 6, @@ -128,14 +115,12 @@ public void notPossibleToReachTheGoal() { 5, "one" ).getResult()); - } @Disabled("Remove to run test") @Test @DisplayName("With the same buckets but a different goal, then it is possible") public void withTheSameBucketsButADifferentGoalThenItIsPossible() { - Result bucketResult = new TwoBucket( 6, 15, @@ -146,14 +131,12 @@ public void withTheSameBucketsButADifferentGoalThenItIsPossible() { assertThat(bucketResult.getTotalMoves()).isEqualTo(10); assertThat(bucketResult.getFinalBucket()).isEqualTo("two"); assertThat(bucketResult.getOtherBucket()).isEqualTo(0); - } @Disabled("Remove to run test") @Test @DisplayName("Goal larger than both buckets is impossible") public void goalLargerThanBothBucketsIsImpossible() { - assertThatExceptionOfType(UnreachableGoalException.class) .isThrownBy(() -> new TwoBucket( 5, @@ -161,7 +144,6 @@ public void goalLargerThanBothBucketsIsImpossible() { 8, "one" ).getResult()); - } } diff --git a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java index 5352f649f..f4b7a49f0 100644 --- a/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java +++ b/exercises/practice/variable-length-quantity/src/test/java/VariableLengthQuantityTest.java @@ -20,127 +20,102 @@ public void setUp() { @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> zero") public void encodeASeriesOfIntegersProducingASeriesOfBytesZero() { - assertThat(variableLengthQuantity.encode(List.of(0x0L))) .isEqualTo(List.of("0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary single byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitrarySingleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x40L))) .isEqualTo(List.of("0x40")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> largest single byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestSingleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x7fL))) .isEqualTo(List.of("0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest double byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestDoubleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x80L))) .isEqualTo(List.of("0x81", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary double byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryDoubleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x2000L))) .isEqualTo(List.of("0xc0", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> largest double byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestDoubleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x3fffL))) .isEqualTo(List.of("0xff", "0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest triple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestTripleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x4000L))) .isEqualTo(List.of("0x81", "0x80", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary triple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryTripleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x100000L))) .isEqualTo(List.of("0xc0", "0x80", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> largest triple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestTripleByte() { - assertThat(variableLengthQuantity.encode(List.of(0x1fffffL))) .isEqualTo(List.of("0xff", "0xff", "0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest quadruple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestQuadrupleBy() { - assertThat(variableLengthQuantity.encode(List.of(0x200000L))) .isEqualTo(List.of("0x81", "0x80", "0x80", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary quadruple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuadrupleB() { - assertThat(variableLengthQuantity.encode(List.of(0x8000000L))) .isEqualTo(List.of("0xc0", "0x80", "0x80", "0x0")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> largest quadruple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesLargestQuadrupleByt() { - assertThat(variableLengthQuantity.encode(List.of(0xfffffffL))) .isEqualTo(List.of("0xff", "0xff", "0xff", "0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> smallest quintuple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestQuintupleBy() { - assertThat(variableLengthQuantity.encode(List.of(0x10000000L))) .isEqualTo(List.of( "0x81", @@ -149,14 +124,12 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesSmallestQuintupleBy() "0x80", "0x0" )); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> arbitrary quintuple byte") public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuintupleB() { - assertThat(variableLengthQuantity.encode(List.of(0xff000000L))) .isEqualTo(List.of( "0x8f", @@ -165,7 +138,6 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuintupleB() "0x80", "0x0" )); - } @Disabled("Remove to run test") @@ -173,7 +145,6 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesArbitraryQuintupleB() @DisplayName("Encode a series of integers, producing a series of bytes. -> maximum " + "32-bit integer input") public void encodeASeriesOfIntegersProducingASeriesOfBytesMaximum32BitInteger() { - assertThat(variableLengthQuantity.encode(List.of(0xffffffffL))) .isEqualTo(List.of( "0x8f", @@ -182,24 +153,20 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesMaximum32BitInteger() "0xff", "0x7f" )); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> two single-byte values") public void encodeASeriesOfIntegersProducingASeriesOfBytesTwoSingleByteValues() { - assertThat(variableLengthQuantity.encode(List.of(0x40L, 0x7fL))) .isEqualTo(List.of("0x40", "0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> two multi-byte values") public void encodeASeriesOfIntegersProducingASeriesOfBytesTwoMultiByteValues() { - assertThat(variableLengthQuantity.encode(List.of(0x4000L, 0x123456L))) .isEqualTo(List.of( "0x81", @@ -209,14 +176,12 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesTwoMultiByteValues() { "0xe8", "0x56" )); - } @Disabled("Remove to run test") @Test @DisplayName("Encode a series of integers, producing a series of bytes. -> many multi-byte values") public void encodeASeriesOfIntegersProducingASeriesOfBytesManyMultiByteValues() { - assertThat(variableLengthQuantity.encode(List.of( 0x2000L, 0x123456L, @@ -242,54 +207,44 @@ public void encodeASeriesOfIntegersProducingASeriesOfBytesManyMultiByteValues() "0x80", "0x0" )); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> one byte") public void decodeASeriesOfBytesProducingASeriesOfIntegersOneByte() { - assertThat(variableLengthQuantity.decode(List.of(0x7fL))) .isEqualTo(List.of("0x7f")); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> two bytes") public void decodeASeriesOfBytesProducingASeriesOfIntegersTwoBytes() { - assertThat(variableLengthQuantity.decode(List.of(0xc0L, 0x0L))) .isEqualTo(List.of("0x2000")); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> three bytes") public void decodeASeriesOfBytesProducingASeriesOfIntegersThreeBytes() { - assertThat(variableLengthQuantity.decode(List.of(0xffL, 0xffL, 0x7fL))) .isEqualTo(List.of("0x1fffff")); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> four bytes") public void decodeASeriesOfBytesProducingASeriesOfIntegersFourBytes() { - assertThat(variableLengthQuantity.decode(List.of(0x81L, 0x80L, 0x80L, 0x0L))) .isEqualTo(List.of("0x200000")); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> maximum 32-bit integer") public void decodeASeriesOfBytesProducingASeriesOfIntegersMaximum32BitInteger() { - assertThat(variableLengthQuantity.decode(List.of( 0x8fL, 0xffL, @@ -298,7 +253,6 @@ public void decodeASeriesOfBytesProducingASeriesOfIntegersMaximum32BitInteger() 0x7fL ))) .isEqualTo(List.of("0xffffffff")); - } @Disabled("Remove to run test") @@ -306,11 +260,9 @@ public void decodeASeriesOfBytesProducingASeriesOfIntegersMaximum32BitInteger() @DisplayName("Decode a series of bytes, producing a series of integers. -> " + "incomplete sequence causes error") public void decodeASeriesOfBytesProducingASeriesOfIntegersIncompleteSequenceC() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> variableLengthQuantity.decode(List.of(0xffL))) .withMessage("Invalid variable-length quantity encoding"); - } @Disabled("Remove to run test") @@ -318,18 +270,15 @@ public void decodeASeriesOfBytesProducingASeriesOfIntegersIncompleteSequenceC() @DisplayName("Decode a series of bytes, producing a series of integers. -> " + "incomplete sequence causes error, even if value is zero") public void decodeASeriesOfBytesProducingASeriesOfIntegersIncompleteSequenceC2() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> variableLengthQuantity.decode(List.of(0x80L))) .withMessage("Invalid variable-length quantity encoding"); - } @Disabled("Remove to run test") @Test @DisplayName("Decode a series of bytes, producing a series of integers. -> multiple values") public void decodeASeriesOfBytesProducingASeriesOfIntegersMultipleValues() { - assertThat(variableLengthQuantity.decode(List.of( 0xc0L, 0x0L, @@ -355,7 +304,6 @@ public void decodeASeriesOfBytesProducingASeriesOfIntegersMultipleValues() { "0x3fff", "0x4000" )); - } } diff --git a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java index a4a0f2a19..0b8eb6537 100644 --- a/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java +++ b/exercises/practice/wordy/src/test/java/WordProblemSolverTest.java @@ -18,223 +18,177 @@ public void setUp() { @Test @DisplayName("just a number") public void justANumber() { - assertThat(solver.solve("What is 5?")).isEqualTo(5); - } @Disabled("Remove to run test") @Test @DisplayName("addition") public void addition() { - assertThat(solver.solve("What is 1 plus 1?")).isEqualTo(2); - } @Disabled("Remove to run test") @Test @DisplayName("more addition") public void moreAddition() { - assertThat(solver.solve("What is 53 plus 2?")).isEqualTo(55); - } @Disabled("Remove to run test") @Test @DisplayName("addition with negative numbers") public void additionWithNegativeNumbers() { - assertThat(solver.solve("What is -1 plus -10?")).isEqualTo(-11); - } @Disabled("Remove to run test") @Test @DisplayName("large addition") public void largeAddition() { - assertThat(solver.solve("What is 123 plus 45678?")).isEqualTo(45801); - } @Disabled("Remove to run test") @Test @DisplayName("subtraction") public void subtraction() { - assertThat(solver.solve("What is 4 minus -12?")).isEqualTo(16); - } @Disabled("Remove to run test") @Test @DisplayName("multiplication") public void multiplication() { - assertThat(solver.solve("What is -3 multiplied by 25?")).isEqualTo(-75); - } @Disabled("Remove to run test") @Test @DisplayName("division") public void division() { - assertThat(solver.solve("What is 33 divided by -3?")).isEqualTo(-11); - } @Disabled("Remove to run test") @Test @DisplayName("multiple additions") public void multipleAdditions() { - assertThat(solver.solve("What is 1 plus 1 plus 1?")).isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("addition and subtraction") public void additionAndSubtraction() { - assertThat(solver.solve("What is 1 plus 5 minus -2?")).isEqualTo(8); - } @Disabled("Remove to run test") @Test @DisplayName("multiple subtraction") public void multipleSubtraction() { - assertThat(solver.solve("What is 20 minus 4 minus 13?")).isEqualTo(3); - } @Disabled("Remove to run test") @Test @DisplayName("subtraction then addition") public void subtractionThenAddition() { - assertThat(solver.solve("What is 17 minus 6 plus 3?")).isEqualTo(14); - } @Disabled("Remove to run test") @Test @DisplayName("multiple multiplication") public void multipleMultiplication() { - assertThat(solver.solve("What is 2 multiplied by -2 multiplied by 3?")).isEqualTo(-12); - } @Disabled("Remove to run test") @Test @DisplayName("addition and multiplication") public void additionAndMultiplication() { - assertThat(solver.solve("What is -3 plus 7 multiplied by -2?")).isEqualTo(-8); - } @Disabled("Remove to run test") @Test @DisplayName("multiple division") public void multipleDivision() { - assertThat(solver.solve("What is -12 divided by 2 divided by -3?")).isEqualTo(2); - } @Disabled("Remove to run test") @Test @DisplayName("unknown operation") public void unknownOperation() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 52 cubed?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("Non math question") public void nonMathQuestion() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("Who is the President of the United States?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject problem missing an operand") public void rejectProblemMissingAnOperand() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject problem with no operands or operators") public void rejectProblemWithNoOperandsOrOperators() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject two operations in a row") public void rejectTwoOperationsInARow() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus plus 2?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject two numbers in a row") public void rejectTwoNumbersInARow() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 plus 2 1?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject postfix notation") public void rejectPostfixNotation() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is 1 2 plus?")) .withMessage("I'm sorry, I don't understand the question!"); - } @Disabled("Remove to run test") @Test @DisplayName("reject prefix notation") public void rejectPrefixNotation() { - assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> solver.solve("What is plus 1 2?")) .withMessage("I'm sorry, I don't understand the question!"); - } } diff --git a/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java b/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java index 614d8ec28..12ed4d794 100644 --- a/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java +++ b/exercises/practice/zebra-puzzle/src/test/java/ZebraPuzzleTest.java @@ -12,7 +12,6 @@ public void residentWhoDrinksWater() { ZebraPuzzle zebraPuzzle = new ZebraPuzzle(); assertThat(zebraPuzzle.getWaterDrinker()).isEqualTo("Norwegian"); - } @Disabled("Remove to run test") @@ -22,7 +21,6 @@ public void residentWhoOwnsZebra() { ZebraPuzzle zebraPuzzle = new ZebraPuzzle(); assertThat(zebraPuzzle.getZebraOwner()).isEqualTo("Japanese"); - } } diff --git a/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java index d8251e35f..b5d399ee9 100644 --- a/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java +++ b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java @@ -3501,18 +3501,31 @@ public static String cleanJavaFormatting(String javaCode) { String trimmed = line.trim(); if (trimmed.isEmpty()) { - if (prevWasAnnotation) { - int nextIdx = i + 1; - while (nextIdx < lines.length && lines[nextIdx].trim().isEmpty()) { - nextIdx++; - } - if (nextIdx < lines.length) { - String nextTrimmed = lines[nextIdx].trim(); - if (nextTrimmed.startsWith("@") || nextTrimmed.startsWith("public ") - || nextTrimmed.startsWith("void ") || nextTrimmed.startsWith("private ") - || nextTrimmed.startsWith("protected ") || nextTrimmed.startsWith("default ")) { - continue; - } + int nextIdx = i + 1; + while (nextIdx < lines.length && lines[nextIdx].trim().isEmpty()) { + nextIdx++; + } + + if (!result.isEmpty()) { + String prevLine = result.get(result.size() - 1); + String prevTrimmed = prevLine.trim(); + if (!prevTrimmed.isEmpty() && Character.isWhitespace(prevLine.charAt(0)) + && prevTrimmed.endsWith("{")) { + continue; + } + } + + if (nextIdx < lines.length) { + String nextLine = lines[nextIdx]; + String nextTrimmed = nextLine.trim(); + if (!nextTrimmed.isEmpty() && Character.isWhitespace(nextLine.charAt(0)) + && nextTrimmed.startsWith("}")) { + continue; + } + if (prevWasAnnotation && (nextTrimmed.startsWith("@") || nextTrimmed.startsWith("public ") + || nextTrimmed.startsWith("void ") || nextTrimmed.startsWith("private ") + || nextTrimmed.startsWith("protected ") || nextTrimmed.startsWith("default "))) { + continue; } } diff --git a/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java b/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java index cf651b381..ba4cb45e4 100644 --- a/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java +++ b/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java @@ -56,4 +56,42 @@ public void testTwo() { assertThat(cleaned).isEqualTo(expected); } + + @Test + @DisplayName("strips blank lines at method boundaries while preserving internal blank lines") + void testCleanJavaFormattingStripsMethodBoundaryBlankLinesOnly() { + String input = """ + public class ExampleTest { + + @Test + @DisplayName("method with extra boundary blank lines") + public void testMethod() { + + int value = 42; + + assertThat(value).isEqualTo(42); + + } + + } + """; + + String cleaned = TemplateRenderer.cleanJavaFormatting(input); + + String expected = """ + public class ExampleTest { + + @Test + @DisplayName("method with extra boundary blank lines") + public void testMethod() { + int value = 42; + + assertThat(value).isEqualTo(42); + } + + } + """; + + assertThat(cleaned).isEqualTo(expected); + } }