Home

Fizz Buzz in Java

Gradle setup

For our build.gradle file:

apply plugin: "java" apply plugin: "eclipse" apply plugin: "idea" repositories { mavenCentral() } dependencies { testCompile "junit:junit:4.12" } test { testLogging { exceptionFormat = 'full' events = ["passed", "failed", "skipped"] } }

Setting up the Tests

Create file src/test/java/FizzBuzzTest.java:

import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FizzBuzzTest { @Test public void testReturnsIntAsString() { assertEquals("2", new FizzBuzz().run(2)); } // @Ignore("Remove to run test") @Test public void testReturnsFizz() { assertEquals("Fizz", new FizzBuzz().run(3)); } @Test public void testReturnsBuzz() { assertEquals("Buzz", new FizzBuzz().run(5)); } @Test public void testReturnsFizzBuzz() { assertEquals("FizzBuzz", new FizzBuzz().run(15)); } }

src/main/java/FizzBuzz.java

For our main Java file running FizzBuzz:

class FizzBuzz { String run(Integer input) { if (input % 15 == 0) { return "FizzBuzz"; } else if (input % 3 == 0) { return "Fizz"; } else if (input % 5 == 0) { return "Buzz"; } else { return Integer.toString(input); } } }

Running tests

Run gradle test to compile and test our FizzBuzz class.

Repository

https://github.com/okeeffed/developer-notes-nextjs/content/java/java-fizz-buzz

Sections


Related