I have used PowerMock with Mockito for mocking final Class.
Following are Maven dependencies for PowerMock and Mockito.
Eg. pom.xml
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.5.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.5.5</version> <scope>test</scope> </dependency>
Scenario
We have final class called TestFinal.java with public method called Send(String parameter).
Need to mock Send method.
How we do that?
Eg: Final Class is as follows
final class TestFinal{ public String send(String input){ //method to process the input String status=Processor.getResult(input); return status; } }
Mocking send method
import java.io.IOException; import java.util.HashMap; import org.junit.Before; 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(TestFinal.class) public class RequestFlowTest { @Test public void shouldTestRequestData() throws Exception { TestFinal testFinal = PowerMockito.mock(TestFinal.class); PowerMockito.when(testFinal.send("testInput")).thenReturn("Success"); String result=testFinal.send("testInput"); org.junit.Assert.assertEquals"Success",result); } }
Advertisements
Leave a Reply