Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
ffs Avatar asked Oct 14 '22 23:10

ffs


2 Answers

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.

like image 123
riorio Avatar answered Oct 17 '22 15:10

riorio


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.

like image 34
Rweinz Avatar answered Oct 17 '22 13:10

Rweinz