您的位置:首页 > 编程语言

powermock如何阻止静态代码块和调用私有方法

2014-04-15 17:58 316 查看
在项目中进行单元测试,发现很多类都采用了静态代码块,而静态代码块在class被容器load的时候就要被执行,如果执行错误就会导致junit单元测试错误,那么如何阻止静态代码块的执行呢?

如果我有一个被测试的Class如下:

package com.roger.test;

public class UnderTestClass {

static {
System.loadLibrary("evil.dll");
}

private final String message = "test";

private String content;

public String getMessage() {
return message;
}

public String  callPrivateContent(){
return getContent();
}

private String getContent(){
content = "private";
return content;
}
}


我在单体测试的时候并没有library 对应的evil.dll 这样运行时就会导致我单元测试的时候错误

解决方法如下:

@SuppressStaticInitializationFor("com.roger.test.UnderTestClass")//阻止静态代码块运行


整体如下:

package com.roger.test;

import java.lang.reflect.Method;

import junit.framework.Assert;

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.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(UnderTestClass.class)
@SuppressStaticInitializationFor("com.roger.test.UnderTestClass")//阻止静态代码块运行
public class TestUnderTestClass {

@Test
public void testGetMessage() throws Exception{
UnderTestClass test = PowerMockito.spy(new UnderTestClass());//创建spy

//断定调用私有方法的方法
PowerMockito.when(test.callPrivateContent()).thenCallRealMethod();
Assert.assertEquals("private", test.callPrivateContent());

//改变私有方法的返回值后,断定调用私有方法的方法
PowerMockito.when(test,"getContent").thenReturn("test2");
Assert.assertEquals("test2", test.callPrivateContent());

//公共方法的断定
PowerMockito.when(test.getMessage()).thenReturn("test1");
Assert.assertEquals("test1", test.getMessage());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐