Skip to main content

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

Popular posts from this blog

[Snippet] CSS - Child element overlap parent

I searched from somewhere and found that a lot of people says a basic concept for implementing this feature looks like below: HTML code: <div id="parent">  <div id="child">  </div> </div> And, CSS: #parent{   position: relative;   overflow:hidden; } #child{   position: absolute;   top: -1;   right: -1px; } However, I had a lot of grand-parents in my case and the above code didn't work. Therefore, I needed an alternative. I presumed that my app uses Boostrap and AngularJs, maybe some CSS from them affects mine. I didn't know exactly the problem, but I believed when all CSS is loaded into my browser, I could completely handle it. www.tom-collinson.com I tried to create an example to investigated this problem by Fiddle . Accidentally, I just changed: position: parent; to position: static; for one of parents -> the problem is solved. Look at my code: <div class="modal-body dn-placeholder-parent-positi...

Selenium - Override javascript functions to ignore downloading process

I have got an issue with downloading process on IE 8. This browser blocks my automatic-download functionality on my app so that I could not work with my test case any more after that. In my case, I didn't care about the file is downloaded or not, I just focus on the result after downloading process finished successfully. Therefore, I found a solution to ignore this process so that I can work normally. I use Primefaces, here is the remote command to trigger the download process <p:remoteCommand name="cmdGenerateDocument" actionListener="#{logic.onGenerateDocument}" update="xrflDocumentCreationPanel" oncomplete="clickDownloadButton();"/> The following is my test case: @Test public void shouldUpdateStep6ToWarningIfStep1IsValidAfterFinished(){ MainPage mainPage = new MainPage(); waitForLoading(mainPage.getDriver()); EmployeeDetailPage empDetailPage = new EmployeeDetailPage(); waitForLoading(empDetailPage.getDriver()); e...

Why Functional Programming Matter

What issues do we concern when implementing and maintaining systems? One of the most concern is debugging during maintenance: "this code crashed because it observed some unexpected value." Then, it turns out that the ideas of  no side effects  and  immutability , which functional programming promotes, can help. Shared mutable data is the root cause Shared mutable data are read and updated by more than one of the methods. Share mutable data structures make it harder to track changes in different parts of your program. An immutable object is an object that can't change its state after it's instantiated so it can't be affected by the actions of a function. It would be a dream to maintain because we wouldn't have any bad surprises about some object somewhere that unexpectedly modifies a data structure. A new thinking: Declarative programming There are two ways thinking about implementing a system by writing a program. - Imperative programming: has...

DevOps for Dummies

Everyone talks about it, but not everyone knows what it is. Why DevOps? In general, whenever an organization adopts any new technology, methodology, or approach, that adoption has to be driven by a business need. Any kind of system that need rapid delivery of innovation requires DevOps (development and operations). Why? DevOps requires mechanisms to get fast feedback from all the stakeholders in the software application that's being delivered. DevOps approaches to reduce waste and rework and to shift resources to higher-value activities. DevOps aims to deliver value (of organization or project) faster and more efficiently. DevOps Capabilities The capabilities that make up DevOps are a broad set that span the software delivery life cycle. The following picture is a reference architecture which provides a template of a proven solution by using a set of preferred methods and capabilities. My Remarks Okay, that sounds cool. What does it simply mean, again? The f...

Java 8 - Persistent data structure

The following is a series of posts about "functional programming in Java" which is the result of my understanding by reading the book " Java 8 in Action: Lambdas, Streams, and Functional-style Programming, by Alan Mycroft and Mario Fusco ". 1. Why functional programming? 2. Functional programming in Java 8 3. Java 8 - Using Functions as Values 4. Java 8 - Persistent data structure Persistent data structure is also known as a simple technique but it's very important. Its other names are functional data structure and immutable data structure. Why is it "persistent"? Their values persist and are isolated from changes happening elsewhere. That's it! This technique is described as below: If you need a data structure to represent the result of a computation, you should make a new one and not mutable an existing data structure. Destructive updates version public static A doSomething(A a){ a.setProp1("new value"); return...