Can I delay a stubbed method response with Mockito?

You could simply put the thread to sleep for the desired time. Watch out tho – such things can really slow down your automated test execution, so you might want to isolate such tests in a separate suite It would look similar to this: when(mock.load(“a”)).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation){ Thread.sleep(5000); return “ABCD1234”; … Read more

Disable @EnableScheduling on Spring Tests

If you don’t want to use profiles, you can add flag that will enable/disable scheduling for the application In your AppConfiguration add this @ConditionalOnProperty( value = “app.scheduling.enable”, havingValue = “true”, matchIfMissing = true ) @Configuration @EnableScheduling public static class SchedulingConfiguration { } and in your test just add this annotation to disable scheduling @TestPropertySource(properties = … Read more

How to Re-run failed JUnit tests immediately?

You can do this with a TestRule. This will give you the flexibility you need. A TestRule allows you to insert logic around the test, so you would implement the retry loop: public class RetryTest { public class Retry implements TestRule { private int retryCount; public Retry(int retryCount) { this.retryCount = retryCount; } public Statement … Read more

Compare Date objects with different levels of precision

There are libraries that help with this: Apache commons-lang If you have Apache commons-lang on your classpath, you can use DateUtils.truncate to truncate the dates to some field. assertEquals(DateUtils.truncate(date1,Calendar.SECOND), DateUtils.truncate(date2,Calendar.SECOND)); There is a shorthand for this: assertTrue(DateUtils.truncatedEquals(date1,date2,Calendar.SECOND)); Note that 12:00:00.001 and 11:59:00.999 would truncate to different values, so this might not be ideal. For that, … Read more

JUnit Testing Exceptions [duplicate]

@Test(expected = Exception.class) Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown. For @Test Junit will consider test as failed if exception is thrown, provided it’s an unchecked exception. If the exception is checked it won’t compile and you will need to use other … Read more

How to use JUnit and Hamcrest together?

If you’re using a Hamcrest with a version greater or equal than 1.2, then you should use the junit-dep.jar. This jar has no Hamcrest classes and therefore you avoid classloading problems. Since JUnit 4.11 the junit.jar itself has no Hamcrest classes. There is no need for junit-dep.jar anymore.