View Ravichandran J.V.'s profile on LinkedIn RJV 's Blog: JUnit and MockItTo test (Arrange, Act, Assert & Verify) Tweet @ravichandranjv


Friday, 9 November 2012

JUnit and MockItTo test (Arrange, Act, Assert & Verify)

A simple scenario of an assert and a setting expectation with MockItTo:

1. @Test
2. public void call_should_return_hello_world(){
// Arrange
3. HelloWorld h=mock(HelloWorld.class);
// Act
4. when(h.sayHello()).thenReturn("Hello World");
// Assert
5. assertEquals("Hello world", h.sayHello());
// Verify
6. verify(h).sayHello();

Line 4 sets the expectation (a la BDD style), that when sayHello() is called the value returned should be the string passed to thenReturn.

Line 5 performs an assertion, totally independent of the mock expectation set.

Line 6 verifies that the method call was made on the mock object "h", at least once, the default.

So, what does this example serve for? It helps as an example to differentiate between the expectation of a JUnit assert from a mock expectation regardless of the type of object on which the method call is made.

Comment Line 5 and Line 6 will fail with

"Wanted but not invoked:
-> at Hello_Mockito.call_should_return_hello_world(
Actually, there were zero interactions with this mock.

Simplify the code with annotations:

public class Hello_Mockito {
// Arrange
HelloWorld h;
public void call_should_return_hello_world(){
//HelloWorld h=mock(HelloWorld.class);
                        // Act
when(h.sayHello()).thenReturn("Hello World");
                       // Assert
assertEquals("Hello World", h.sayHello());
           // Verify

No comments: