Mocking Final Classes with Mockito

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
Tagged with: , , , , , ,
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: