القائمة الرئيسية

الصفحات

A simple way to mock objects without using mock unit testing framework

When writing unit test, there are some cases that I have to mock objects:
  1. It makes sense to mock provided objects by libraries (APIs) such as FacesContext (JSF) because of no real environment running.
  2. It makes sense to mock a lower layer objects and it is already tested, for example: mocking Dao layer objects when testing Service layer (Service calls Dao).
At beginning I was aware of Mockito (a mocking framework) in order to overcome the issue. And currently, I am interested in another way like an alternative because it looks more simple. That is just create mock objects manually and just do anything we want. I've just known this approach from Primefaces' source code. :)

Follow my simple example below and we can see what different from these 2 ways are:

I have an interface Foo and a class Bar

public interface Foo {
String greet();
}

public class Bar {
public String greet(Foo foo){
return foo.greet();
}
}

Using Mockito example:

public class MockitoExampleTest {
private Foo foo;

@Before
public void setup(){
foo = Mockito.mock(Foo.class);
Mockito.when(foo.greet()).thenReturn("Hello world!");
}

@Test
public void barGreets(){
Bar bar = new Bar();
Assert.assertEquals(bar.greet(foo), "Hello world!");
}
}

Simple mock example:

public class FooMock implements Foo {

public String greet() {
return "Hello world!";
}

}

public class SimpleMockExampleTest {
private Foo foo;

@Before
public void setup(){
foo = new FooMock();
}

@Test
public void barGreets(){
Bar bar = new Bar();
Assert.assertEquals(bar.greet(foo), "Hello world!");
}
}

The following is Primefaces' test code that shows the same idea above:

FacesContext context = new FacesContextMock(attributes); 
context.setViewRoot(new UIViewRoot());

References:
[1]. https://examples.javacodegeeks.com/core-java/mockito/mockito-hello-world-example/ 
[2]. https://github.com/primefaces/primefaces

Comments