mockito模拟静态方法

这里要用到使用powerMock 
注意点: 
1 @RunWith(PowerMockRunner.class) 
2 PowerMockito.mockStatic(StaticTest.class); 

Java代码   收藏代码
  1. package com.eyu.ahxy.module.staticd;  
  2.   
  3. import static org.hamcrest.Matchers.equalTo;  
  4. import static org.junit.Assert.assertThat;  
  5.   
  6. import org.junit.Test;  
  7. import org.junit.runner.RunWith;  
  8. import org.powermock.api.mockito.PowerMockito;  
  9. import org.powermock.modules.junit4.PowerMockRunner;  
  10.   
  11. @RunWith(PowerMockRunner.class)  
  12. public class StaticTest {  
  13.   
  14.     @Test  
  15.     public void test1() {  
  16.         PowerMockito.mockStatic(StaticTest.class);  
  17.         PowerMockito.when(StaticTest.static1()).thenReturn("static");  
  18.         String result = StaticTest.static1();  
  19.         assertThat(result, equalTo("static"));  
  20.         PowerMockito.verifyStatic();//验证静态方法是否执行
  21.     }  
  22.   
  23.     public static String static1() {  
  24.         return "test1";  
  25.     }  
  26.   
  27. }  



powmock的maven依赖: 

 
org.powermock 
powermock-api-mockito 
1.6.3 
test 
 

 
org.powermock 
powermock-module-junit4 
1.6.3 
test 

本文转自:http://huangyunbin.iteye.com/blog/2176728

你可能感兴趣的:(mockito模拟静态方法)