Closed johanhaleby closed 9 years ago
From johan.ha...@gmail.com on February 04, 2011 01:32:48
This is because it's impossible to byte-code manipulate Java System classes such as Math. It's documented here: https://code.google.com/p/powermock/wiki/MockSystem http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/
From johan.ha...@gmail.com on February 04, 2011 01:33:04
Status: WontFix
From michal.r...@gmail.com on February 04, 2011 01:38:32
thanks a lot for your reply.
From michal.r...@gmail.com on February 03, 2011 16:39:14
Why mocking of jre (system) classes works different than mocking of other (non jre) ?
1.I am testing MathUserr class. MathUserr calls static method OtherClass.myRandom(). 2.To mock OtherClass.myRandom() i need to: 2.1. add @PrepareForTest({ OtherClass.class}) annotation 2.2. call PowerMockito.mockStatic(OtherClass.class); 2.3. declare stubbing: when(OtherClass.myRandom()).thenReturn(2.0); 3.Now if class under test (MathUserr) calls OtherClass.myRandom(), it gets 2.0d value.
OK... it is clear. but now I describe the way, we mock JRE's java.lang.Math class.
1.I am testing MathUserr class. MathUserr calls static method Math.random(); 2.To mock Math.random() i need to: 2.1. add @PrepareForTest({ MathUserr.class}) annotation (WOOW, why MathUserr instead of Math???) 2.2. call PowerMockito.mockStatic(Math.class); 2.3. declare stubbing: when(Math.random()).thenReturn(2.0); 3.Now if class under test (MathUserr) calls OtherClass.myRandom(), it gets 2.0d value.
Everything in the same way, except of point 2.1.
Why it works in this way ? Is it documented ? Thanks in advance for any information :)
Source code that I am desribing: #############################################SOURCE CODE START#### package tp.check;
import static org.junit.Assert.; import static org.mockito.BDDMockito.;
import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class) @PrepareForTest({ OtherClass.class, MathUserr.class }) public class StaticTests { @Test public void mockMyStaticMethod() throws Exception { // given MathUserr u = new MathUserr(); PowerMockito.mockStatic(OtherClass.class); when(OtherClass.myRandom()).thenReturn(2.0);
}
class MathUserr{ public double jreRandom(){ return Math.random(); }
}
class OtherClass{ public static double myRandom(){ return 22.0; // ;) } }
#############################################SOURCE CODE END####
Original issue: http://code.google.com/p/powermock/issues/detail?id=312