- PowerMock - Home
- PowerMock - Overview
- PowerMock - Environment Setup
- PowerMock - First Application
- PowerMock - Mock Static
- PowerMock - Mock Private
- PowerMock - Mock Final
- PowerMock - Mock New
- PowerMock - Bypass Encapsulation
- PowerMock - Supress Behavior
- PowerMock Useful Resources
- PowerMock - Quick Guide
- PowerMock - Useful Resources
- PowerMock - Discussion
PowerMock - Supress Behavior
PowerMock allows to suppress unwanted behavior like call to unwanted constructor, static method, static block or even fields. For example, suppress method of PowerMockito can be used to suppress call to a constructor using following syntax.
PowerMockito.suppress(PowerMockito.constructor(BasePortfolio.class));
Example
Below is the complete example of supressing behavior.
File: BasePortfolio.java
package com.tutorialspoint;
public class BasePortfolio {
private boolean servicesConfigured = false;
public BasePortfolio(){
//configure services
servicesConfigured = true;
}
public boolean isServicesConfigured(){
return servicesConfigured;
}
}
File: Portfolio.java
package com.tutorialspoint;
public class Portfolio extends BasePortfolio {
public Portfolio(){
super();
}
}
Let's test the Portfolio class.
File: PortfolioTester.java
package com.tutorialspoint;
import static org.junit.Assert.assertEquals;
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( Portfolio.class )
public class PortfolioTester {
Portfolio portfolio;
@Test
public void testServicesNotConfigured(){
PowerMockito.suppress(PowerMockito.constructor(BasePortfolio.class));
portfolio = new Portfolio();
assertEquals ( "Base constructor not called, services not configured",
false, portfolio.isServicesConfigured());
}
@Test
public void testServicesConfigured(){
portfolio = new Portfolio();
assertEquals ( "Base constructor called, services configured",
true, portfolio.isServicesConfigured());
}
}
Output
Once you are done with creating the source files, you are ready for this step, which is compiling and running your program. To do this, keep PortfolioTester.Java file tab active, right click within the content area of PortfolioTester.Java and click on Run As > Junit Test option. If everything is fine with your application, this will run the test case in Eclipse JUnit Window and you can see the test case result as green means it is passed otherwise red being failed.