- It makes sense to mock provided objects by libraries (APIs) such as FacesContext (JSF) because of no real environment running.
- 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).
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