A simple way to mock objects without using mock unit testing framework - The Koch Family
The Koch Family The Koch Family

Latest news

جاري التحميل ...

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



If you like the content of our blog, we hope to stay in constant communication, just enter your email to subscribe to the blog's express mail to receive new blog updates, and you can send a message by clicking on the button next ...

إتصل بنا

About the site

author The Koch Family <<  Welcome! I'm so glad that you stopped by Your Modern Family blog. Together, we will talk about raising kids, organizing the home and saving money! and Tips & tricks and more…

< Learn more ←

Blog stats

Sparkline 2513183

All Copyrights Reserved

The Koch Family

2020