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.

How to Crop Image in Java

Sometimes, you need to crop an image. In order to crop image in java, we will use the method subimage from BufferedImage class.

bufferedImage.getSubimage(x, y, width, height);

Example:
This static method will return the cropped image given the starting x and y coordinate and the width and height that will be cropped from the image.

/**
     * Crops an image to the specified region
     * @param bufferedImage the image that will be crop
     * @param x the upper left x coordinate that this region will start
     * @param y the upper left y coordinate that this region will start
     * @param width the width of the region that will be crop
     * @param height the height of the region that will be crop
     * @return the image that was cropped.
     */
    public static BufferedImage cropImage(BufferedImage bufferedImage, int x, int y, 
                                          int width, int height){
        BufferedImage croppedImage = bufferedImage.getSubimage(x, y, width, height);
        return croppedImage;
    }

To read an image from a file, we can do:

File imageFile = new File("C:/Javapointers/image.jpg");
BufferedImage bufferedImage = ImageIO.read(imageFile);

This method will return the image buffered from the file.

After cropping the image, we can now save or write the file to the file system using:

File pathFile = new File("C:/Javapointers/image-crop.jpg");
ImageIO.write(image,"jpg", pathFile);

where image is the cropped image.

Create Cookie Example in Java

Here is a simple cookie example that will be added to the response and to the user’s browser.

Creating a Cookie

@RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(HttpServletResponse response) {
        //create a cookie with name 'website' and value 'javapointers'
        Cookie cookie = new Cookie("website", "javapointers");
        //set the expiration time
        //1 hour = 60 seconds x 60 minutes
        cookie.setMaxAge(60 * 60);
        //add the cookie to the  response
        response.addCookie(cookie);
        //return the jsp with the response
        return "home";
    }

Reading a Cookie

@RequestMapping(value = "/home/cookie", method = RequestMethod.GET)
    public String readCookie(HttpServletRequest request) {
        //get all cookies
        Cookie[] cookies = request.getCookies();
        //iterate each cookie
        for (Cookie cookie : cookies) {
            //display only the cookie with the name 'website'
            if (cookie.getName().equals("website")) {
                System.out.println(cookie.getValue());
            }
        }
        return "home";
    }

Checking your browser

Below, we can verify that our cookie has been successfully added to the browser.

cookie

 

Page 1 of 1312345...10...Last »