Mockito : how to verify method was called on an object created within a method?

I am new to Mockito. Given the class below, how can I use Mockito to verify that someMethod was invoked exactly once after foo was invoked? public class Foo { public void foo(){ Bar bar = new Bar(); bar.someMethod(); } } I would like to make the following verification call, verify(bar, times(1)).someMethod(); where bar is … Read more

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

I’m using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have final MyClass myClassSpy = Mockito.spy(myInstance); Mockito.when(myClassSpy.method1()).thenReturn(myResults); The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception. The only reason I’m using mocks is so that later, … Read more

Why doesn’t JUnit provide assertNotEquals methods?

Does anybody know why JUnit 4 provides assertEquals(foo,bar) but not assertNotEqual(foo,bar) methods? It provides assertNotSame (corresponding to assertSame) and assertFalse (corresponding to assertTrue), so it seems strange that they didn’t bother including assertNotEqual. By the way, I know that JUnit-addons provides the methods I’m looking for. I’m just asking out of curiosity. 11 Answers 11

How to run test methods in specific order in JUnit4?

I want to execute test methods which are annotated by @Test in specific order. For example: public class MyTest { @Test public void test1(){} @Test public void test2(){} } I want to ensure to run test1() before test2() each time I run MyTest, but I couldn’t find annotation like @Test(order=xx). I think it’s quite important … Read more

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

What is the main difference between @Before and @BeforeClass and in JUnit 5 @BeforeEach and @BeforeAll @After and @AfterClass According to the JUnit Api @Before is used in the following case: When writing tests, it is common to find that several tests need similar objects created before they can run. Whereas @BeforeClass can be used … Read more

How to verify that a specific method was not called using Mockito?

How to verify that a method is not called on an object’s dependency? For example: public interface Dependency { void someMethod(); } public class Foo { public bar(final Dependency d) { … } } With the Foo test: public class FooTest { @Test public void dependencyIsNotCalled() { final Foo foo = new Foo(…); final Dependency … Read more

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

How can I use JUnit4 idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } I recall that there is an annotation or an Assert.xyz … Read more