//Preconditions Addition addition = new Addition(); int x = 1; int y = 1; //Execution int actual = addition.add(x, y); //Assertions assertEquals(2, actual); } }
Calculator calculator = new Calculator(); /* * Cannot test in isolation * Added noise, is the input relevant? * Is the test actually valid? */ Subtraction subtraction = new Subtraction(2,2); int actual = calculator.make(subtraction); assertEquals(0, actual); } }
/* * CoffeeGrinder adds noise * Not testing in isolation */ CoffeeMaker coffeeMaker = new CoffeeMaker( new CoffeeGrinder(), new WaterTank()); coffeeMaker.steam(); } }
/* * Don't use values specific to your app. * They add noise. Make the test fragile. * Use random variable names to show intent. * Any two arrays in this case. */ Array<String> one = Array.of( new String[]{"foo"} ); Array<String> another = Array.of( new String[]{"bar"} ); assertThat(one, not(equalTo(another))); } }
Exception { final CountDownLatch singleCount = new CountDownLatch(1); //Equal to the number of threads final AtomicBoolean didRun = new AtomicBoolean(); //Be safe1 Executors.callable(new Runnable() { public void run() { didRun.set(true); singleCount.countDown(); //Call at the end of execution } }).call(); singleCount.await(2, TimeUnit.SECONDS); //Don't want infinite blocking tests Assert.assertTrue(didRun.get()); } } 1. generally