This question already has answers here:
PowerMock, mock a static method, THEN call real methods on all other statics
(2 answers)
Closed 5 years ago.
I have a utility class that I need to do some unit testing, but within this utility class I have methods that depend on others in that same utility class.
For that I'm using the following dependencies:
jUnit:4.12
Mockito: 2.8
Powermock: 1.7
As it's already evident that I am using Java to perform my code.
Now go to the example code:
public final class AppUtils {
private AppUtils () {
throw new UnsupportedOperationException("This class is not instantiable.");
}
public static int plus(int a, int b) {
return a + b;
}
public static float average(int a, int b) {
return ((float) AppUtils.plus(a, b)) / 2;
}
}
And the unit test:
#RunWith(PowerMockRunner.class)
#PrepareForTest({AppUtils.class})
public class AppUtilsTest {
#Test
public void testPlus() { //This test must be good.
assertEquals(6, AppUtils.plus(4, 2));
}
#Test
public void testAverage() {
PowerMockito.mockStatic(AppUtils.classs);
when(AppUtils.plus(anyInt())).thenReturn(6);
assertEquals(3f, AppUtils.average(4, 3), 1e-2d);
}
}
That way I did my unit test, but this throws me an error because it tells me that the expected result does not correspond to the actual one.
expected: 3.000f
actual: 0
This is because PowerMock by using the mockStatic() method replaces all static implementations for your defines, but if you do not define the result of one static method then it returns 0.
If anyone can help me, I thank you.
UnitTests verify the public observable behavior of the code under test.
The public observable behavior of the CUT includes the return values and the communication with its dependencies.
This means that you treat that other methods as if they where private, just looking at the outcome of the method called.
BTW:
There is no such rule that "utility classes" (in the sense that they provide basic or common functionality) must have static methods only.
That's just a common misconception driven by the habit to name classes with only static methods "utility classes".
It is absolutely OK to make all your utility methods non static and instantiate the class before using it.
Dependency Injection (and not the Singelton Pattern) will help you to have only one instance used all around your program...
Related
Suppose I have the following class :
public class Math {
public int mult(int a, int b) {
return 4;
}
public int mul (int a, int b) {
return mult(a,b);
}
}
And the following test class :
public class TestMockito {
Math testMath;
#Before
public void create () {
testMath = *mock*(Math.class);
when(testMath.mult(1,2).thenReturn(2);
}
#Test
public void test() {
System.out.println(testMath.mul(1,2));
}
}
Why does mul(1,2) called in test() not use when(testMath.mult(1,2).thenReturn(2); ?
Is there any other way to mock a method being used inside another method that is being tested ?
Cheers
You usually do not mock the code under test (unless it is an abstract class).
You usually mock other classes (the dependencies) your CUT communicates with.
The reason why your test does not work (as you expect) is that the mock is not an object of the real class (which is the reason why we mock it BTW....). It has been derived by the mocking framework not to behave like the original code but like it has been configured for the test.
If you really want the real methods being called in the mock (which is not what you want most of the time) you need to tell mockito that when creating the mock:
mock(ClassToBeMocked.class,Mockito.CALL_REAL_METHODS);
I am new to Mockito, please help in understanding the basic.
According to me above code is supposed to print 5 when mocked.add(6,7) gets called , but add() method is not getting called and the code prints 0.. why ? any solution for this code ?
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
class Calc{
int add(int a,int b){
System.out.println("add method called");
return a+b;
}
}
class MockTest{
public static void main(String[] args) {
Calc mocked=mock(Calc.class);
when(mocked.add(2,3)).thenReturn(5);
System.out.println(mocked.add(6,7));
}
}
In order to get result of 5, you have to pass the exact params as when you set up the when..then. Otherwise mockito will return a 'default' value (which is 0 for integer:
What values do mocks return by default?
In order to be transparent and unobtrusive all Mockito mocks by
default return 'nice' values. For example: zeros, falseys, empty
collections or nulls. Refer to javadocs about stubbing to see exactly
what values are returned by default.
If you want to return 5 for any integer then use:
when(mocked.add(Mockito.any(Integer.class),Mockito.any(Integer.class))).thenReturn(5);
A "mock" is just an empty dummy object that simulates behaviour of a "real" object. If you define a behaviour such like when(mocked.add(2,3)).thenReturn(5); you specifically tell this mock what to do, when it receives those exact values.
mocked.add(6,7) will return 0 at that point, since you haven't defined its behaviour for those values and therefore uses a default value. So if you want to cover all possible inputs, you can go with the solution #MaciejKowalski posted and use the generic matchers like Mockito.any(Integer.class).
Still I believe it is not clear how to correctly handle mocks. Mocks are a way of providing external dependencies to a system-under-test without the need to set up a whole dependency tree. The real methods inside that class are usually not called. That's what something like when(mocked.add(2,3)).thenReturn(5); means. It tells the mock to behave like the real dependency without actually having it at hand.
An example could look like this:
public class TestClass {
private ExternalDependency dep;
public void setDep(ExternalDependency dep) {
this.dep = dep;
}
public int calculate() {
return 5 + dep.doStuff();
}
}
public class ExternalDependency {
public int doStuff() {
return 3;
}
}
Now in your test code you can use mocks like this:
#Test
public void should_use_external_dependency() {
// Aquire a mocked object of the class
ExternalDependency mockedDep = Mockito.mock(ExternalDependency.class);
// Define its behaviour
Mockito.when(mockedDep.doStuff()).thenReturn(20);
TestClass sut = new TestClass();
sut.setDep(mockedDep);
// should return 25, since we've defined the mocks behaviour to return 20
Assert.assertEquals(25, sut.calculate());
}
If sut.calculate() is invoked, the method in ExternalDependency should not be really called, it delegates to the mocked stub object instead. But if you want to call the real method of the real class, you could use a Spy instead with Mockito.spy(ExternalDependency.class) or you could do that with when(mockedDep.doStuff()).thenCallRealMethod();
In JMockit, there are types that are outright un-mockable (like java.lang.Class) or are really bad ideas to mock (like java.lang.Math, as stated in this question).
How do you use Verifications on these types? Using the linked question as an example, how would I verify that Math.pow() got called with the right arguments?
By way of example, this test passes even though I call Math.pow() but I check for Math.min() in the Verifications - how could I make this fail?
public class TestTest {
public static class MyClass {
public double foo() {
return Math.pow(2, 3);
}
}
#Tested MyClass mc;
// #Mocked java.lang.Math math;
#Test
public void testCalendar() throws Throwable {
double d = mc.foo();
assertThat(d, is(8.0));
new FullVerificationsInOrder() {{
Math.min(42.0, 17.0);
}};
}
}
Adding the commented-out line, to mock Math, only leads to disastrous results due to fouling up classloaders etc that rely on java.lang.Math. Making it #Injectable instead of #Mocked has no effect since all methods are static.
So how could I verify it?
Hi I really hope you can help me, I feel like I've been pulling my hair out for days.
I'm trying to write unit tests for a method A. Method A calls a static method B. I want to mock static method B.
I know this has been asked before, but I feel Android has matured since then, and there must be a way to do such a simple task without re-writing the methods I want to test.
Here is an example, first the method I want to test:
public String getUserName(Context context, HelperUtils helper) {
if(helper == null){
helper = new HelperUtils();
}
int currentUserId = helper.fetchUsernameFromInternet(context);
if (currentUserId == 1) {
return "Bob";
} else {
return "Unknown";
}
}
Next the static method I want to mock:
public class HelperUtils {
public static int fetchUsernameFromInternet(Context context) {
int userid = 0;
Log.i("HelperUtils ", "hello");
return userid;
}
}
In other languages this is so easy but I just can't make it work in Android.
I've tried Mockito, but it appears static methods aren't supported
HelperUtils helper = Mockito.mock(HelperUtils.class);
Mockito.when(helper.fetchUsernameFromInternet(getContext())).thenReturn(1);
This errors
org.mockito.exceptions.misusing.MissingMethodInvocationException
I've tried Powermock but I'm not completely sure this is supported by Android. I managed to get powermock running using androidCompile in my gradle file but I get this error:
Error:Execution failed for task ':app:dexDebugAndroidTest'. com.android.ide.common.process.ProcessException:
Not to mention PowerMockito.mockStatic(HelperUtils.class); Doesn't return anything, so I don't know what to pass into my getUsername method!
Any help would be so very much appreciated.
Static methods aren't related to any object - your helper.fetchUsernameFromInternet(...) is the same (but a bit confusing) as HelperUtils.fetchUsernameFromInternet(...) - you should even get a compiler warning due to this helper.fetchUsernameFromInternet.
What's more, instead of Mockito.mock to mock static methods you have to use: #RunWith(...), #PrepareForTest(...) and then PowerMockito.mockStatic(...) - complete example is here: PowerMockito mock single static method and return object
In other words - mocking static methods (and also constructors) is a bit tricky. Better solution is:
if you can change HelperUtils, make that method non-static and now you can mock HelperUtils with the usual Mockito.mock
if you can't change HelperUtils, create a wrapper class which delegates to the original HelperUtils, but doesn't have static methods, and then also use usual Mockito.mock (this idea is sometimes called "don't mock types you don't own")
I did this way using PowerMockito.
I am using AppUtils.class, it contains multiple static methods and functions.
Static function:
public static boolean isValidEmail(CharSequence target) {
return target != null && EMAIL_PATTERN.matcher(target).matches();
}
Test case:
#RunWith(PowerMockRunner.class)
#PrepareForTest({AppUtils.class})
public class AppUtilsTest {
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(AppUtils.class);
PowerMockito.when(AppUtils.isValidEmail(anyString())).thenCallRealMethod();
}
#Test
public void testValidEmail() {
assertTrue(AppUtils.isValidEmail("name#email.com"));
}
#Test
public void testInvalidEmail1() {
assertFalse(AppUtils.isValidEmail("name#email..com"));
}
#Test
public void testInvalidEmail2() {
assertFalse(AppUtils.isValidEmail("#email.com"));
}
}
Edit 1:
Add following imports:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
Hope this would help you.
You can use mockito latest version i.e 3.4.+ which allows static mocking
https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#48
Here are some solutions:
Modify your static method as a non-static method or wrap your static method with a non-static method, and then directly use Mockito to mock the non-static method in the Android Test.
If you don't want to change any original code, you can try to use a dexmaker-mockito-inline-extended to mock static methods and final methods in the Android Test. I successfully mocked the static methods with it. Check this
solution.
Use a Robolectric in the Unit test and then use PowerMock to mock the static methods in the Unit Test.
I use Mockito 1.8.0 so I do not have AnyVararg. Upgrading to later version of Mockito is not on cards from my team at the moment. So please bear with me.
What the class looks like:
public abstract class Parent {
public void someMethod(String a, String b)
{
//.....
}
public void foo(String a, String... b)
{
//.....
}
}
public class Child extends Parent{
public void bar() {
someMethod(a,b);
foo(a,b,c);
methodToFailUsingSpy();
}
}
Unit tests
#Test
public void someTest() {
private spyOfChild = //initialize here;
doReturn("Something")).when(spyOfChild).methodToFailUsingSpy();
/* Tried using this, but did not help.
doCallRealMethod().when(spyOfChild).foo(anyString());
*/
spyOfChild.bar();
}
Problem -
When the spy sees someMethod(), it calls the real method in the abstract class. But when it sees foo(), it tries to find a matching stubbed method i.e control goes to Mockito's MethodInterceptorFilter, since it is not able to find a mock, it throws java.lang.reflect.InvocationTargetException.
I do not want foo() to be mocked. I want the real method to be called like it happens in someMethod(). Can someone explain if it is because of using method with variable length arguments with a spy?
This is a bug in Mockito.
https://groups.google.com/forum/#!msg/mockito/P_xO5yhoXMY/FBeS4Nf4X9AJ
Your example is quite complicated, to reproduce the problem is very simple:
class SimpleClass {
public String varargsMethod(String... in) {
return null;
}
public void testSpyVarargs() {
SimpleClass sc = Mockito.spy(new SimpleClass());
sc.varargsMethod("a", "b");
}
}
Even this will produce the error you describe, and the workaround suggested in the link doesn't work for me.
Unfortunately to get around this you will need to upgrade Mockito. Changing to version 1.9.5 makes the above run fine, plus you get the varargs matchers as you say (although note that your problem isn't to do with matchers but how Mockito handles spied varargs methods).
I don't think there were too many huge changes between 1.8.0 and 1.9.5, it shouldn't be too painful.