Extremely Serious

Month: April 2022

Mocking Static Method with Mockito

Sample codes for mocking a static with Mockito.

The StringUtil class is a very trivial class that converts the text to all capitalized.

StringUtil class

public final class StringUtil {

    private StringUtil() {}

    public static String upperCase(String text) {
        return text.toUpperCase();
    }
}

Mocking the StringUtil.upperCase method

Stubbing the StringUtil.upperCase method to return test if test is passed as argument.

Dependencies Required

org.junit.jupiter:junit-jupiter-engine:5.8.2
org.mockito:mockito-inline:4.4.0

StringUtilTest class

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

public class StringUtilTest {

    @Test
    void staticMethod() {
        try (var utilities = mockStatic(StringUtil.class)) {
            utilities.when(() -> StringUtil.upperCase("test")).thenReturn("test");
            assertEquals("test", StringUtil.upperCase("test"));
        }
    }
}

Checking if a Directory is Empty Using Stream

var dirPath = Paths.get("C:\\tmp", "sample"); //The path to be tested.
if (dirPath.toFile().isDirectory()) { //Check if the directory exists.
    try (Stream<Path> entries = Files.list(dirPath)) {
        if (entries.findFirst().isEmpty()) {
            System.out.printf("%s is empty.", dirPath);
        }
    }
}

Generating Random Number

Listing the Available Random Algorithms

System.out.printf("%-13s| %s\n-------------|---------------------\n", "Group", "Name");
java.util.random.RandomGeneratorFactory.all()
        .sorted(java.util.Comparator.comparing(java.util.random.RandomGeneratorFactory::name))
        .forEach(factory -> System.out.printf("%-13s| %s\n", factory.group(), factory.name()));

The output is similar to the following:

Group        | Name
-------------|---------------------
LXM          | L128X1024MixRandom
LXM          | L128X128MixRandom
LXM          | L128X256MixRandom
LXM          | L32X64MixRandom
LXM          | L64X1024MixRandom
LXM          | L64X128MixRandom
LXM          | L64X128StarStarRandom
LXM          | L64X256MixRandom
Legacy       | Random
Legacy       | SecureRandom
Legacy       | SplittableRandom
Xoroshiro    | Xoroshiro128PlusPlus
Xoshiro      | Xoshiro256PlusPlus

Check from the following address on how to choose which algorithm to choose:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html#algorithms

Creating an instance of RandomGenerator

The default algorithm (i.e. L32X64MixRandom)

var generator = java.util.random.RandomGenerator.getDefault();

The specific algorithm (e.g. L64X128MixRandom)

var generator = java.util.random.RandomGenerator.of("L64X128MixRandom");

Use the static method RandomGenerator.of and pass the name of the algorithm.

Generating Random Number

Use one of the following instance methods of the RandomGenerator class:

  • nextDouble()
  • nextDouble(double bound)
  • nextDouble(double origin, double bound)
  • nextFloat()
  • nextFloat(float bound)
  • nextFloat(float origin, float bound)
  • nextInt()
  • nextInt(int bound)
  • nextInt(int origin, int bound)
  • nextLong()
  • nextLong(long bound)
  • nextLong(long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

 var generator = java.util.random.RandomGenerator.of("Random");
 System.out.println(generator.nextInt());

The output is a random integer number.

Generating Random Number Using Streams

Use one of the following instance methods of RandomGenerators class to create streams:

  • doubles()
  • doubles(double origin, double bound)
  • doubles(long streamSize)
  • doubles(long streamSize, double origin, double bound)
  • ints()
  • ints(int origin, int bound)
  • ints(long streamSize)
  • ints(long streamSize, int origin, int bound)
  • longs()
  • longs(long origin, long bound)
  • longs(long streamSize)
  • longs(long streamSize, long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

var generator = java.util.random.RandomGenerator.of("Random");
var randomInt = generator.ints(100, 1, 100)
        .filter(number -> number % 2 == 0 )
        .findFirst();
randomInt.ifPresent(System.out::println);

The output is a random integer number.