I've been trying for a while to mock my codes. I'm newby on mocking so lots of things ahead of me to catch. I'm using Powermockito with Mockito and Easymock integration.
I'm having difficulties with mocking a method which is inside the method I wanted to test. So here is an example of the situation I faced:
public class trialClass {
public static int try2(){
return 3;
}
public static int try(int a){
return try2() + a;
}
}
and my test class is:
#RunWith(PowerMockRunner.class)
#PrepareForTest(trial.class)
public class trialTest {
#Before
public void setUp() throws Exception {
PowerMockito.mockStatic(trial.class);
//Here I expect try2() to return 10, even it return 3
PowerMockito.when(trial.try2()).thenReturn(10);
}
#Test
public void testtry() throws Exception {
//After try2() returns 10 recursively inside my try() method,
//I expect result to be 11
Assert.assertEquals(11, trial.try(1));
}
}
This question of mine actually comes from my session variable. My session holds some value and an X method returns that value. All I need is to mock that X method recursively and this question just simulates this case.
Thanks for your help guys.
You need to use Mockito.CALLS_REAL_METHODS
So in your test setup:
PowerMockito.mockStatic(trial.class, CALLS_REAL_METHODS);
EDIT
It occurred to me that you might not want to change to EasyMock instead of Mockito, in that case please disregard...
Partial mocking is the keyword you are after. You don't want to mock everything, just try2(). You should use the PowerMock.mockStaticPartial(Class, String...) method.
Instead of
PowerMockito.mockStatic(trialClass.class);
Use
PowerMock.mockStaticPartial(trialClass.class, "try2");
And then do the actual mocking.
Also note that you defined the clas as trialClass in the code above, but use trial.class in the second code...
Please find an updated version of your TrialTest.java using EasyMock with PowerMock as a solution. PowerMock is easy to configure and does not interfere with most existing jars. You only need a few JARS
powermock-easymock-X.X.X-full.jar
Easymock-X.X.jar
You had some issues with your code that I fixed:
Code Issue: try is a Java keyword so it cannot be used in method name (e.g., try(int a)).
Code Quality: Use Java Object instead of Java primitive (e.g., Use Integer instead of int).
Code Quality: trialClass is a poor Java class name (e.g., Use upperCase for Java class name, don't use the generic word Class unless for educational purposes), maybe Trial.
Here's the updated code:
Trial.java (CUT)
public class Trial {
public static Integer try2() {
return 3;
}
public static Integer try1(int a) {
return try2() + a;
}
}
Working Test Class: TrialTest.java
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Trial.class)
public class TrialTest {
#Before
public void setUp() throws Exception {
/* Setup */
PowerMock.mockStaticPartial(Trial.class, "try2");
/* Mocks */
// Here I expect try2() to return 10, even it return 3
EasyMock.expect(Trial.try2()).andReturn(10).atLeastOnce();
PowerMock.replayAll();
}
#Test
public void testtry() throws Exception {
// After try2() returns 10 recursively inside my try() method,
// I expect result to be 11
/* Test */
Integer result = Trial.try1(1);
/* Asserts */
PowerMock.verifyAll();
Assert.assertEquals(new Integer(11), result);
}
}
Related
My code doesn't meet the sonarqube code coverage the following piece of constructor says it needs test in sonarqube, I have written the following code to test it but it is not covering the code? can some one help me where I am going wrong?
#Test
public void OrderBuilderIT() {
errorQueue.equals("amq:ORDER.T.SYSTEM.ERROR");
}
public OrderBuilder(String errorQueue) {
this.errorQueue = errorQueue;
}
the code does not seem to be covered
I am assuming that you are trying to test the constructor call for the class with the error queue field value that you are passing while constructing and expecting the same value to be asserted. Actually, your check does nothing in terms of an assertion.
Below is an assumption that you may be trying to achieve. Also, should cover your sonar issue.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
public class SomeConstructorTest {
private OrderBuilder orderBuilder;
#Test
public void orderBuilderTestWithIncorrectErrorQueueMessage(){
String expected = "amq:ORDER.T.SYSTEM.ERROR";
String errorQueue = "dummyString";
orderBuilder = new OrderBuilder(errorQueue);
assertThat(expected, is(errorQueue)); // should fail if you are asserting string content
}
}
I'm trying to stub this getKeyFromStream method, using the 'any' matchers. I've tried being more explicit and less explicit (anyObject()), but it seems like no matter what I try, this stub will not return the fooKey in my unit test.
I'm wondering if it is because it is protected or there is something else I'm missing or doing incorrectly. I have other when/then statements throughout the tests that are working but for some reason here, it is not.
Note: The getKeyFromStream generally uses a byteArrayInputStream, but I'm trying to match it with an InputStream, I've tried both to no avail.
public class FooKeyRetriever() //Mocked this guy
{
public FooKey getKey(String keyName) throws KeyException {
return getKeyFromStream(getKeyStream(keyName, false), keyName);
}
//Stubbed this method to return a key object which has been mocked
protected FooKey getKeyFromStream(InputStream keyStream, String keyName){
//Some code
return fooKey;
}
}
Unit Test
#Mock
private FooKeyRetriever mockKeyRetriever;
#Mock
private FooKey fooKey;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void testGetFooKey() throws Exception {
when(foo.getKeyFromStream(any(InputStream.class),any(String.class))).thenReturn(fooKey);
FooKey fooKey = mockKeyRetriever.getKey("irrelevant_key");
assertNotNull(fooKey);
}
The problem with your unit-test is, that you are trying to mock a method of your actual class which you want to test but you can't actually invoke a mock method as this will return null unless you declare a mocked return value on that invoked method. Usually, you only mock external dependencies.
There are actually two ways to create test-objects: mock and spy. The primer one will create a new object based on the class you provided which has internal state null and also return null on every invoked method. That's why you need to define certain return values for method invocations. spy on the other hand creates a real object and intercepts method invocations if "mock definitions" are defined for certain methods.
Mockito and PowerMock provide two ways of defining your mocked methods:
// method 1
when(mockedObject.methodToMock(any(Param1.class), any(Param2.class),...)
.thenReturn(answer);
when(mockedObject, method(Dependency.class, "methodToMock", Parameter1.class, Parameter2.class, ...)
.thenReturn(answer);
or
// method 2
doReturn(answer).when(mockedObject).methodToMock(param1, param2);
The difference is, that the method 1 will execute the methods implementation while the later one won't. This is important if you deal with spy objects as you sometimes don't want to execute the real code inside the invoked method but instead just replace the code or return a predefined value!
Although Mockito and PowerMock provide a doCallRealMethod() which you can define instead of doReturn(...) or doThrow(...), this will invoke and execute the code within your real object and ignores any mocked method return statements. Though, this is not that useful in your case where you want to mock a method of your class under test.
A method implementation can be "overwritten" by
doAnswer(Answer<T>() {
#Override
public T answer(InvocationOnMock invocation) throws Throwable {
...
}
)
where you simply can declare what the logic of the invoked method should be. You can utilize this to return the mock result of the protected method therefore like this:
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import java.io.InputStream;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class FooKeyRetrieverTest {
#Test
public void testGetFooKey() throws Exception {
// Arrange
final FooKeyRetriever sut = spy(new FooKeyRetriever());
FooKey mockedKey = mock(FooKey.class);
doReturn(mockedKey)
.when(sut).getKeyFromStream(any(InputStream.class), anyString());
doAnswer(new Answer<FooKey>() {
public FooKey answer(InvocationOnMock invocation) throws Throwable {
return sut.getKeyFromStream(null, "");
}
}).when(sut).getKey(anyString());
// Act
FooKey ret = sut.getKey("test");
// Assert
assertThat(ret, sameInstance(mockedKey));
}
}
The code above works, however note that this has the same semantic as simply declaring a return value for the getKey(...) as
doReturn(mockedKey).when(sut).getKey(anyString());
Trying to modify only getKeyFromStream(...) with something like this:
doReturn(mockedKey)
.when(sut).getKeyFromStream(any(InputStream.class), anyString());
without modifying getKey(...) of your System-Under-Test (SUT) won't achieve anything as the real code of getKey(...) would be executed. If you however mock the sut-object, you could not invoke the method in your // Act section as this would return null. If you try
doCallRealMethod().when(sut).getKey(anyString());
on a mock object, the real method woulb be called and as mentiond beforehand, this would also invoke the real implementations of getKeyFromStream(...) and getKeyStream(...) regardless what you specified as mock-method.
As you probably can see by yourself, mocking methods of your actual class under test is not that useful and puts more burden to you than it provides any good. Therefore, it's up to you or your enterprise' policy if you want or need to test private/protected methods at all or if you stick to testing only the public API (which I would recommend). You also have the possibility to refactor your code in order to improve testability although the primary intent of refactoring should be to improve the overall design of your code.
How can I make the 3rd test to check for the existence of cause1 in the message of the exception? I also listed in the first two tests that have drawbacks. First is not checking for the message second needs a lot of boilerplate code.
public class CheckExceptionsWithMockitoTest {
#Test(expected = RuntimeException.class)
public void testExpectedException1() {
A a = new A();
a.doSomethingThatThrows();
}
#Test
public void testExpectedException2() {
A a = new A();
try {
a.doSomethingThatThrows();
fail("no exception thrown");
} catch (RuntimeException e) {
assertThat(e.getMessage(), org.hamcrest.Matchers.containsString("cause1"));
}
}
#Test
public void testExpectedException3() {
A a = new A();
A spyA = org.mockito.Mockito.spy(a);
// valid but doesnt work
// doThrow(new IllegalArgumentException()).when(spyA).doSomethingThatThrows();
// invalid but in the spirit of what i want
//chekThrow(RuntimeException.class,containsString("cause1")).when(spyA).doSomethingThatThrows();
}
}
I couldn't find in Mockito something that works but there is something that looks like could be possible (at the level of syntax) and capabilities.
Using catchexception I created the test like this
import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
public class CheckExceptionsWithMockitoTest{
//...
#Test
public void testExpectedException3() {
A a = new A();
verifyException(a,IllegalArgumentException.class)
.doSomethingThatThrows();
//if more details to be analized are needed
assertThat(
(IllegalStateException) caughtException(),
allOf(
is(IllegalStateException.class),
hasMessageThat(
containsString("is not allowed to add counterparties")),
hasNoCause()));
//more asserts could come
assertNotNull(a);
}
}
Use catch-exception library, or I guess that the solution you are looking for is your second implementation.
#expected doesn't provide any way to assert on the thrown exception except for its class, so you can't avoit try/catching (not that much boiler plate code !)
Mockito doesn't provide something likes a verifyThrows method.
So you can trade try/catching for an additional library : using catch-exception, you'll be able to catch exception in a single line and have it ready for further assertion(s).
Sample source code
A a = new A();
when(a).doSomethingThatThrows();
then(caughtException())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("is not allowed to add counterparties")
.hasNoCause();
Dependencies
'com.googlecode.catch-exception:catch-exception:1.2.0'
If A is your system under test, it doesn't make any sense to mock it, and it rarely makes sense to spy on it. Your implementation in testExpectedException2 is the right one; the boilerplate code is necessary because without a try block Java will not let any code run after the method is intercepted (as I described in this previous SO answer).
Though Mockito won't be any help, JUnit will. The #Test(expected=foo) parameter actually has a more-flexible alternative, the built-in ExpectedException JUnit rule:
public class CheckExceptionsWithMockitoTest {
#Rule public ExpectedException thrown = ExpectedException.none();
#Test
public void testExpectedException1() {
A a = new A();
thrown.expect(RuntimeException.class);
thrown.expectMessage(containsString("cause1"));
a.doSomethingThatThrows();
}
}
Mockito would come in handy in a separate test checking whether your method wraps an arbitrary exception while preserving its message, which would look roughly like this:
#Test
public void doSomethingShouldWrapExceptionWithPassedMessage() {
Dependency dependency = Mockito.mock(Dependency.class);
when(dependency.call()).thenThrow(new IllegalArgumentException("quux"));
A a = new A(dependency);
thrown.expect(RuntimeException.class);
thrown.expectMessage(containsString("quux"));
a.doSomethingThatThrows();
}
Be careful to avoid the temptation to make this a common pattern in your tests. If you are catching an exception thrown from your system under test, you're effectively ceding control back to the SUT's consumer. There should be little left to test in the method afterwards, except the properties of the exception and MAYBE the state of your system, both of which should be rare enough that try/catch boilerplate is forgivable.
If you have the opportunity to use scala, scalaTest's fun suite has concise way of testing exceptions using intercept (http://www.scalatest.org/getting_started_with_fun_suite).
It's as simple as
test(a list get method catches exceptions){
intercept[IndexOutBoundsException]{
spyListObject.get(-1)
}
}
You could potentially write your tests to your java project in scala if you are looking for easy to write / clear test. But this may present other challenges.
Updated answer for 06/19/2015 (if you're using java 8)
Using assertj-core-3.0.0 + Java 8 Lambdas
#Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
.isInstanceOf(IllegalArgumentException.class);
}
Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html
Using catchexception I created the test like this
import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
public class CheckExceptionsWithMockitoTest{
//...
#Test
public void testExpectedException3() {
A a = new A();
verifyException(a,IllegalArgumentException.class)
.doSomethingThatThrows();
//if more details to be analized are needed
assertThat(
(IllegalStateException) caughtException(),
allOf(
is(IllegalStateException.class),
hasMessageThat(
containsString("is not allowed to add counterparties")),
hasNoCause()));
//more asserts could come
assertNotNull(a);
}
}
If you have a look in Mockito.class on spy method it creates mock with spiedInstance:
public static <T> T spy(T object) {
return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
.spiedInstance(object)
.defaultAnswer(CALLS_REAL_METHODS));
}
In MockSettings it is possible to register Invocation listeners: https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/listeners/InvocationListener.html
I created simple listener which stores all reported invocations:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.mockito.listeners.InvocationListener;
import org.mockito.listeners.MethodInvocationReport;
public class StoringMethodInvocationListener implements InvocationListener {
private List<MethodInvocationReport> methodInvocationReports = new ArrayList<>();
#Override
public void reportInvocation(MethodInvocationReport methodInvocationReport) {
this.methodInvocationReports.add(methodInvocationReport);
}
public List<MethodInvocationReport> getMethodInvocationReports() {
return Collections.unmodifiableList(methodInvocationReports);
}
}
After the invocation you can go through reports and find the one needed and verify that stored throwable is the one expected.
Example:
StoringMethodInvocationListener listener = new StoringMethodInvocationListener();
Consumer mock2 = mock(Consumer.class, withSettings()
.spiedInstance(consumerInstance)
.defaultAnswer(CALLS_REAL_METHODS)
.invocationListeners(listener));
try {
mock2.listen(new ConsumerRecord<String, String>(RECEIVER_TOPIC, 0, 0, null, "{}"));
} catch (Exception e){
//nothing
}
Assert.notEmpty(listener.getMethodInvocationReports(), "MethodInvocationReports list must not be empty");
Assert.isInstanceOf(BindException.class, listener.getMethodInvocationReports().get(1).getThrowable());
To mock a static method powermock giving an exception while expect().
#Test
public void testRegistrarService()
{
mockStatic(IdGenerator.class);
expect(IdGenerator.generateNewId()).andReturn(42L);
long actualId=serTestObj.registerService();
replay(IdGenerator.class);
verify(IdGenerator.class);
assertEquals(42L,actualId);
}
public class ServiceRegistrator
{
public long registerService()
{
long id = IdGenerator.generateNewId();
return id;
}
}
public class IdGenerator
{
public static long generateNewId()
{
return System.currentTimeMillis();
}
}
Exception is:
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at home.powermock.testServiceRegistrator.testRegistrarService(testServiceRegistrator.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at com.intellij.rt.execution.junit2.JUnitStarter.main(JUnitStarter.java:31)
how to mock staic method,while m using powerMock
i'm using intelliJ idea,how to resolve that exception.
Your code is missing the annotation
#PrepareForTest(IdGenerator.class)
In my case I was missing the following method in my test class
#ObjectFactory
/**
* Configure TestNG to use the PowerMock object factory.
*/
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
Once I added it, I got rid of the "no last call on a mock available" error.
You need to put the replay before the actual call to the method.
EDIT: I think part of the problem may be caused because of your imports. Try not to import static powermock and static easymock (I've found that I often confuse myself and forget which one I need to call replay on).
Try running the following code. If it doesn't run correctly, then it may be because of a problem with the particular version of PowerMock/EasyMock/Junit that you have.
TestClass:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest(IdGenerator.class)
public class TestClass {
#Test
public void testRegistrarService()
{
ServiceRegistrator serTestObj = new ServiceRegistrator();
PowerMock.mockStatic(IdGenerator.class);
expect(IdGenerator.generateNewId()).andReturn(42L);
PowerMock.replay(IdGenerator.class);
long actualId=serTestObj.registerService();
PowerMock.verify(IdGenerator.class);
assertEquals(42L,actualId);
}
}
IdGenerator:
public class IdGenerator {
public static long generateNewId()
{
return System.currentTimeMillis();
}
}
ServiceRegistrator:
public class ServiceRegistrator {
public long registerService()
{
long id = IdGenerator.generateNewId();
return id;
}
}
This question has been here for a long time but I'll try to give to it an aswer to explain what i did to resolve this problem.
First of all you have to use these two annotations:
#RunWith(PowerMockRunner.class)
This annotation let the current test class know what to use to run his tests, this is useful because we can use PowerMockRunner instead of JUnitRunner
#PrepareForTest(IdGenerator.class)
This annotation is used to prepare the class "IdGenerator" to be used in the test, prepare means that we will be able to mock the static methods as we do to the public methods
After added these two annotations we have to be sure we are using the right packages provided by PowerMock:
1) PowerMock:
Import: import org.powermock.api.easymock.PowerMock;
Use: We will use PowerMock to mock (and not only) our static method with the following code line
PowerMock.mockStatic(IdGenerator.class);
2) EasyMock:
Import: import org.easymock.EasyMock;
Use: We are going to use EasyMock to fake our object to be returned by our static method:
EasyMock.expect(IdGenerator.generateNewId()).andReturn(42L);
These was two examples on what are used PowerMock and EasyMock, and here I'll try to explain the code and what it does:
mockStatic(IdGenerator.class);
//We mock our IdGenerator class which have the static object
expect(IdGenerator.generateNewId()).andReturn(42L);
//We fake our method return object, when we'll call generateNewId()
//method it will return 42L
//With expecting we "record" our this method and we prepare it to be
//changed (it will return our decided value)
replay(IdGenerator.class);
//We go to perform our methods "registered" with the expect method
//inside the IdGenerator class, in this case with replay we just apply
//the changes of the expect to the method generateNewId()
long actualId = serTestObj.registerService();
//We create our object (which inside have a non static method that
//use generateNewId() static method)
verify(IdGenerator.class);
//We verify that the our faked method have been called
assertEquals(42L,actualId);
//We see if the two values are matching
Pay attention because replay must be used before you create the new object (actualId in this example) that will call the static faked methods.
Also do a lot of attention on what you are importing, for a distraction i was using
PowerMockito.mockStatic(className.class);
//from import org.powermock.api.mockito.PowerMockito;
Instead of
PowerMock.mockStatic(className.class);
//from import org.powermock.api.easymock.PowerMock;
I hope that this answer is clear and complete
By the way here i'll refer you to some useful links:
PowerMock Static Documentation on GitHub
Mvn Repository PowerMock Libraries
See you :D
My situation:
I would like to add a new test. And I need to mock one static method X of Service class.
Unfortunately existing tests are using this static method in some way.
And when I mock X method using PowerMock then other test failed.
What is more I shouldn't touch other tests.
Is there any opportunity to mock static methods for one test only? ( using PowerMock).
Thanks in advance.
Sure, it is possible! The only time when you could run into problems is if you are trying to test multiple threads at the same time... I put an example of how to do it below. Enjoy.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest(IdGenerator.class)
public class TestClass {
#Test
public void yourTest()
{
ServiceRegistrator serTestObj = new ServiceRegistrator();
PowerMock.mockStatic(IdGenerator.class);
expect(IdGenerator.generateNewId()).andReturn(42L);
PowerMock.replay(IdGenerator.class);
long actualId = IdGenerator.generateNewId();
PowerMock.verify(IdGenerator.class);
assertEquals(42L,actualId);
}
#Test
public void unaffectedTest() {
long actualId = IdGenerator.generateNewId();
PowerMock.verify(IdGenerator.class);
assertEquals(3L,actualId);
}
}
TestClass
public class IdGenerator {
public static long generateNewId()
{
return 3L;
}
}
The easiest way to solve your problem is create new test class and place your tests there.
You can also wrap up this static class with normal class hidden behind interface in your code and stub this interface in your tests.
Last thing you can try is to stub each method of your static class in #SetUp method using:
Mockito.when(StaticClass.method(param)).thenCallRealMethod();
and stub particular method in your test using:
Mockito.when(Static.methodYouAreInterested(param)).thenReturn(value);
For those looking to achieve this using Mockito with PowerMocks, this can be done by adding the #PrepareForTest annotation to the tests themselves that need to mock out the values instead of the test class itself.
In this example, let's pretend there is SomeClass that has a static function (returnTrue()) that always returns true like so:
public class SomeClass {
public static boolean returnTrue() {
return true;
}
}
This example shows how we can mock out the static call in one test and allow the original functionality to stay the same in another.
#RunWith(PowerMockRunner.class)
#Config(constants = BuildConfig.class)
#PowerMockIgnore({"org.mockito.*", "android.*"})
public class SomeTest {
/** Tests that the value is not mocked out or changed at all. */
#Test
public void testOriginalFunctionalityStays()
assertTrue(SomeClass.returnTrue());
}
/** Tests that mocking out the value works here, and only here. */
#PrepareForTest(SomeClass.class)
#Test
public void testMockedValueWorks() {
PowerMockito.mockStatic(SomeClass.class);
Mockito.when(SomeClass.returnTrue()).thenReturn(false);
assertFalse(SomeClass.returnTrue())
}
}