发布时间:2019-07-29 18:01:36
使用junit测试Java静态私有方法,通过以下案例进行分析:
测试目标类如下:
1234567891011121314151617181920 package cn.outofmemory.junit;public class TestTarget { /** * 移除正则表达式中需要转义的字符 * @param w word * @return 移除正则表达式中需要转义的字符 * @author Administrator * @date 2015-7-11 */ private static String convert4Regex(String w) { if (w == null) { return null; } String[] convertedChars = {"\\",".","+","*","(",")","{","}","[","]","?","/","^","$","|"}; for (String c : convertedChars) { w = w.replace(c, "\\" + c); } return w; }}
测试方法:
123456789 @Testpublic void testConvert4Regex() throws Exception { String input = "A+"; String expected = "A\\+"; Method targetMethod = TestTarget.class.getDeclaredMethod("convert4Regex", String.class); targetMethod.setAccessible(true); Object actual = targetMethod.invoke(TestTarget.class, new Object[]{input}); assertEquals(expected,actual); }
这个问题只有查看junit4源码中,相应的方法是怎么实现的,就可以解答你的问题。具体如下:
TestCase类的runTest()方法中,有代码如:runMethod = getClass().getMethod(fName, (Class[]) null);这说明junit4的默认运行器只检查了测试方法参数是否为空,不为空就不会被当成测试方法。
TestSuite类的addTestMethod()方法中,会检查是否为public、void修饰,以及其他检测。你可以看看junit源码~