🎉 I'm releasing 12 products in 12 months! If you love product, checkout my new blog workingoutloud.dev

Back to home

Java Fizzbuzz

    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.

    Personal image

    Dennis O'Keeffe

    @dennisokeeffe92
    • Melbourne, Australia

    Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
    I am currently working on Visibuild.

    1,200+ PEOPLE ALREADY JOINED ❤️️

    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    Java Fizzbuzz

    Introduction

    Share this post