How to use Verify in Mockito

When doing unit test, you do some assertions to check the equality between your expected result and the actual result. When you use mock objects in unit test, you may also need no to verify in Mockito that the mock object had done specific methods.

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use:

verify(mockObject).someMethodOfMockObject(someArgument);

If the method was called multiple times, and you want to verify that it was called for specific times, lets say 3 times, then we use:

verify(mockObject, times(3)).someMethodOfMockObject(someArgument);

times() means the number of invocations you expect.

To better understand how verify in mockito works, check the example below.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VerifyTest {

    @Mock
    private List mockList;

    @Test
    public void testMockListAdd() {
        String addString = "some string";
        mockList.add(addString);

        //verify that the add method was called with argument 'some string'
        verify(mockList).add(addString);
    }

    @Test
    public void testMockListAddMultiple() {
        String addString = "some string multiple";
        mockList.add(addString);
        mockList.add(addString);
        mockList.add(addString);

        //verify that the add method was called with argument 'some string'
        verify(mockList, times(3)).add(addString);
    }
}

Difference between Spy and Mock in Mockito

Often you heard developers how to spy and mock in Mockito in unit test but what are the difference between spy and mock in Mockito API? Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it.

When using mock objects, the default behavior of the method when not stub is do nothing. Simple means, if its a void method, then it will do nothing when you call the method or if its a method with a return then it may return null, empty or the default value.

While in spy objects, of course, since it is a real method, when you are not stubbing the method, then it will call the real method behavior. If you want to change and mock the method, then you need to stub it.

Consider the example below as a comparison.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MockSpy {

    @Mock
    private List mockList;

    @Spy
    private List spyList = new ArrayList();

    @Test
    public void testMockList() {
        //by default, calling the methods of mock object will do nothing
        mockList.add("test");
        assertNull(mockList.get(0));
    }

    @Test
    public void testSpyList() {
        //spy object will call the real method when not stub
        spyList.add("test");
        assertEquals("test", spyList.get(0));
    }

    @Test
    public void testMockWithStub() {
        //try stubbing a method
        String expected = "Mock 100";
        when(mockList.get(100)).thenReturn(expected);

        assertEquals(expected, mockList.get(100));
    }

    @Test
    public void testSpyWithStub() {
        //stubbing a spy method will result the same as the mock object
        String expected = "Spy 100";
        //take note of using doReturn instead of when
        doReturn(expected).when(spyList).get(100);

        assertEquals(expected, spyList.get(100));
    }
}

When shoud you use mock or spy? If you want to be safe and avoid calling external services and just want to test the logic inside of the unit, then use mock. If you want to call external service and perform calling of real dependency, or simply say, you want to run the program as it is and just stub specific methods, then use spy. So that’s the difference between spy and mock in mockito.

How to Mock using Mockito

In this example, we will demonstrate how to mock using mockito. This is a simple demonstration on how to use Mockito to mock external classes in a JUnit test. When doing unit testing, you are testing only the logical algorithm of the class. It should not be dependent to other class or service. That’s why we mock the external service, or other dependency. You should know the difference between a unit test and an integration test.

For a start, add the dependency of Mockito to your project.

Consider the MyClass to be the class under test.

package com.javapointers;

public class MyClass {

    public boolean isNameKey(Model model) {
        return model.getKey().equals("name");
    }

    public String getAttributeString(Model model) {
        if (model.getAttribute().equals("primary")) {
            return "is primary";
        } else {
            return "invalid attribute";
        }
    }
}

class Model {
    String key;
    String attribute;

    public Model(String key, String attribute) {
        this.key = key;
        this.attribute = attribute;
    }

    public String getKey() {
        return key;
    }

    public String getAttribute() {
        return attribute;
    }
}

And the test class for MyClass is MyClassTest. In our test class, we use annotations of Mockito, and we need to initialize the annotation by running the unit test with MockitoJUnitRunner.class or we use MockitoAnnotations.initMocks(this). By using annotation @Mock, we define the object to be a Mock Object, thus we should define how the object will respond when its public methods were called. Below is the code of MyClassTest.java

package com.javapointers;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    @Mock
    private Model mockModel;

    private MyClass myClass;

    @Before
    public void setUp() throws Exception {
        myClass = new MyClass();
    }

    @Test
    public void isNameKey_modelKeyIsName() {
        when(mockModel.getKey()).thenReturn("name");

        boolean isNameKey = myClass.isNameKey(mockModel);
        assertTrue(isNameKey);
    }

    @Test
    public void isNameKey_modelKeyIsNotName() {
        when(mockModel.getKey()).thenReturn("something");

        boolean isNameKey = myClass.isNameKey(mockModel);
        assertFalse(isNameKey);
    }

    @Test
    public void getAttributeString_attributeIsPrimary() {
        when(mockModel.getAttribute()).thenReturn("primary");

        String attributeString = myClass.getAttributeString(mockModel);
        assertEquals("is primary", attributeString);
    }

    @Test
    public void getAttributeString_attributeIsNotPrimary() {
        when(mockModel.getAttribute()).thenReturn("secondary");

        String attributeString = myClass.getAttributeString(mockModel);
        assertEquals("invalid attribute", attributeString);
    }
}

We stub the mock object by using when and thenReturn methods. Thus we can create different scenario when a certain object was passed to our class.

Get all Request Parameters in Java

In this tutorial, we’ll show you how to get all request parameters in java. Ideally, the server should know the parameter names that was sent by the client browser. I have created a simple Spring Controller that gets a request from the client and redirect the user to another page that displays all his request parameters and its values.

Create A Servlet Controller

In our Controller, we take a parameter HttpServletRequest which contains the client request including its parameters.

@Controller
@RequestMapping("/sample")
public class SampleController {

@RequestMapping(value = "/get", method= RequestMethod.GET)
public ModelAndView getParameters(HttpServletRequest request){
    Enumeration enumeration = request.getParameterNames();
    Map<String, Object> modelMap = new HashMap<>();
    while(enumeration.hasMoreElements()){
        String parameterName = enumeration.nextElement();
        modelMap.put(parameterName, request.getParameter(parameterName));
    }
    ModelAndView modelAndView = new ModelAndView("sample");
    modelAndView.addObject("parameters", modelMap);
    return modelAndView;
}
}

To get all request parameters in java, we get all the request parameter names and store it in an Enumeration object. Our Enumeration object now contains all the parameter names of the request. We then iterate the enumeration and get the value of the request given the parameter name.

We store the the name and its value in a Map and add it to a ModelAndView and redirect to sample.jsp. Below is the sample.jsp file:

<%@ page import="java.util.Map" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Display All Request Parameters</title>
</head>
<body>
<h4>List of Request Parameter Names and its Values</h4>
    <%
        Map<String, Object> modelMap = (Map<String, Object>) request.getAttribute("parameters");
        for(String key: modelMap.keySet()){
            out.print(key);
            out.print(" : ");
            out.print(modelMap.get(key));
            out.print("<br />");
        }
    %>
</body>
</html>

Testing our WebApp

To test it, we type the url in the browser:

http://localhost:8080/sample/get?name=javapointers&language=java&version=8

When we hit Enter, the resulting page is below:

get-all-request-parameters

Java Convert Image to Base64 String and Base64 to Image

In this post, we will be converting an image to base64 string so that it can be save to a database, more accurately in a blob type column.

Encode Image to Base64 String

The below method will encode the Image to Base64 String. The result will be a String consisting of random characters, representing the image. This characters can then be save to the database. A blob type column is more applicable when saving an image to the database since a blob column can hold large amount of data.

public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

Decode Base64 String to Image

Meanwhile, you can also decode your base64 string to an image to be save or sent to the client. Below is a method on how to decode base64 string to image.

public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

For example, if the data/string came from a client request, if the base64 string starts with something like data:image/png;base64,iVBORw0KGgoAA….. you should remove data:image/png;base64, . Therefore, your base64 string should starts with eg. iVBORw0KGgoAA.

Page 1 of 1412345...10...Last »