Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created November 16, 2016 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/8fdf27bd3739ecedf592d841766420b2 to your computer and use it in GitHub Desktop.
Save nielsutrecht/8fdf27bd3739ecedf592d841766420b2 to your computer and use it in GitHub Desktop.
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
public class UnitTestExample {
private UnitUnderTest unit;
@Before
public void setup() {
//Recreate instance before evert @Test to get it in a known state
unit = new UnitUnderTest();
}
@Test
public void testIntFoo() {
Assert.assertEquals(42, unit.intFoo());
}
@Test
public void testStringFoo() {
Assert.assertEquals("42", unit.stringFoo());
}
@Test
public void testIntBar() {
int value = unit.intBar();
if(value < 1 || value > 6) {
fail("Invalid value: " + value);
}
}
@Test
public void testStringBar() {
int value = Integer.parseInt(unit.stringBar());
if(value < 1 || value > 6) {
fail("Invalid value: " + value);
}
}
@Test
public void testMult() {
assertEquals(2, unit.mult(1, 2));
assertEquals(2, unit.mult(2, 1));
assertEquals(10, unit.mult(2, 5));
assertEquals(-10, unit.mult(-2, 5));
}
}
import java.util.Random;
public class UnitUnderTest {
private Random random = new Random();
public int intFoo() {
return 42;
}
public String stringFoo() {
return Integer.toString(intFoo());
}
public int intBar() {
return random.nextInt(6) + 1;//Throw dice
}
public String stringBar() {
return Integer.toString(intBar());
}
public int mult(int input, int factor) {
return input * factor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment