招聘网站建设公司,视频发布播放网站建设,东营工程造价信息网,seo哪个软件好问题
Java类中private方法通常只能被其所属类的调用#xff0c;其他类只能望而却步#xff0c;单元测试private方法也就一筹莫展。
尝试解法#xff1a;
在测试时#xff0c;手动将private改为public#xff0c;测试完后再将其改回。将测试方法写进private方法的所属类…问题
Java类中private方法通常只能被其所属类的调用其他类只能望而却步单元测试private方法也就一筹莫展。
尝试解法
在测试时手动将private改为public测试完后再将其改回。将测试方法写进private方法的所属类中这样就能调用private方法了。
上述解法虽然可行但这些解法或多或少地违背单元测试应遵守AIR原则。
单元测试在线上运行时感觉像空气AIR那样透明但在测试质量的保障上却是非常关键的。好的单元测试宏观上来说具有自动化、独立性、可重复执行的特点。
AAutomatic自动化IIndependent独立性RRepeatable可重复
解法
先创建一个测试目标类App作为示例目标是测试App类中private方法callPrivateMethod()
public class App {public void doSomething() {callPrivateMethod();}private String callPrivateMethod() {return Private method is called.;}}一
我们可以用Java的反射特性来突破private的限制从而对private方法进行单元测试
单元测试代码
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import org.junit.Assert;
import org.junit.Test;public class AppTest {Testpublic void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {App app new App();Method privateMethod app.getClass().getDeclaredMethod(callPrivateMethod);privateMethod.setAccessible(true);Assert.assertEquals(Private method is called., privateMethod.invoke(app));}
}二
引入第三方工具如Spring测试框架。
引入依赖
dependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion5.3.5/versionscopetest/scope
/dependency单元测试代码
import static org.junit.Assert.*;import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;public class AppTest {Testpublic void test() {App app new App();assertEquals(Private method is called., //ReflectionTestUtils.invokeMethod(app, callPrivateMethod, null));}}参考
Junit测试private方法阿里巴巴Java开发手册How do I test a private function or a class that has private methods, fields or inner classes?