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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With