Spring-boot的单元测试网上有了很多,当项目是可以使用spring-boot正常运行时,只要在测试类上添加如下配置就使用@Autowired的方式进行单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)

现在的场景时,我要测试的时这个类中的某个私有方法的功能,代码如下

@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();
        Method myPricateMothod= clazz.getDeclaredMethod("myPricateMothod", String.class);
        myPricateMothod.setAccessible(true);
        // 执行这个service,不要使用clazz.newInstance(),这个方法是新new一个对象
        myPricateMothod.invoke(service, "myparam");
    }
}
05-23 14:32