ffs
ffs

Reputation: 107

How can I mock a dependency of java.util.Random class?

Suppose in a class I have a dependency on java.util.Random class. Since random is a concrete class and not backed by an interface, how can I mock the dependency? Should I extend the random class and override the methods.

I was initially using Math.random() but since it was a static method, what can I do to mock it? How do I mock static method for unit testing.

Upvotes: 6

Views: 2378

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

A reason for mocking such a class would be testing, what about instead of mocking you make it return the same "random" values every time so you can assert predictable results in your test. You can achieve that by passing a Random instance with a seed.

Random rand = new Random(1L);
System.out.println(rand.nextInt());

And now nextInt will return the same number every time it runs

Upvotes: 1

Rweinz
Rweinz

Reputation: 190

You can use PowerMockito. It's an extension to mockito and it let's you mock static methods.

https://www.baeldung.com/intro-to-powermock

public class CollaboratorWithStaticMethods {
    public static String firstMethod(String name) {
        return "Hello " + name + " !";
    }
 
    public static String secondMethod() {
        return "Hello no one!";
    }
 
    public static String thirdMethod() {
        return "Hello no one again!";
    }
}

@Test
public void TestOne() {
    mockStatic(CollaboratorWithStaticMethods.class);

    when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()))
    .thenReturn("Hello Baeldung!");
}



example taken from link.

Upvotes: 1

riorio
riorio

Reputation: 6826

Instead of using directly the java.util.Random class, create and call a MyRandomUtility class that you inject into your class.

In this class, you only need to have a method that wraps the java.util.Random class

class MyRandomUtility {

  public Int getRandom(){
      java.util.Random.nextInt().....
  }
}

And in your main class, you can include the MyRandomUtility.

In the tests, you can now easily mock it.

Upvotes: 3

Related Questions