Spring-boot的单元测试网上有了不少,当项目是可使用spring-boot正常运行时,只要在测试类上添加以下配置就使用@Autowired的方式进行单元测试java
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class)
如今的场景时,我要测试的时这个类中的某个私有方法的功能,但私有方法中存在使用@Autowired的对象,代码以下spring
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) public class Test { @Autowired private Service service; @Test public void test() throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { // 获取class Class<? extends Service> clazz = service.getClass(); // 获取方法,注意param的类型 Method myPricateMothod= clazz.getDeclaredMethod("myPricateMothod", String.class); myPricateMothod.setAccessible(true); // 执行这个service,不要使用clazz.newInstance(),这个方法是新new一个对象 myPricateMothod.invoke(service, "myparam"); } }