Mockito: Trying to spy on method is calling the original method

Let me quote the official documentation: Important gotcha on spying real objects! Sometimes it’s impossible to use when(Object) for stubbing spies. Example: List list = new LinkedList(); List spy = spy(list); // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn(“foo”); // You have to use doReturn() for stubbing … Read more

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once. In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup … Read more

Maven does not find JUnit tests to run

By default Maven uses the following naming conventions when looking for tests to run: Test* *Test *Tests (has been added in Maven Surefire Plugin 2.20) *TestCase If your test class doesn’t follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.

How do you assert that a certain exception is thrown in JUnit tests?

It depends on the JUnit version and what assert libraries you use. For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984 If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984 The original answer for JUnit <= 4.12 was: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } Though answer … Read more

How do I test a class that has private methods, fields or inner classes?

If you have somewhat of a legacy Java application, and you’re not allowed to change the visibility of your methods, the best way to test private methods is to use reflection. Internally we’re using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)