Spring-boot單元測試(私有方法測試)

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");
    }
}
相關文章
相關標籤/搜索