栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring单元测试001-如何测试私有方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring单元测试001-如何测试私有方法

Spring单元测试私有方法
想要测试某类中的私有方法,必须通过反射。
反射获取私有方法有两种方式,一种是直接new对象,然后通过getClass;一种是extends要测试的类,然后this.getClass().getSuperclass()。对于不需要依赖spring容器的私有方法,用上述两种获取方式都可以。但是对于依赖bean的私有方法,必须采用extends的方式
原因如下:
new对象的方式不会将该类注入spring容器,故也不会获取到该类中通过spring容器注入的bean。反应在结果中就是该bean报空指针异常,而用第二种方式的话,由于@RunWith(SpringRunner.class)表示将当前测试类加入spring容器,故可将当前测试类及其超类注入bean。所以使用当前测试类的实例就可以获取到其超类的私有方法,并且通@SpringBootTest获取到项目中的其他bean

package com.test.impl;

import com.test.ServerApplication.class;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServerApplication.class)
public class XXXTest extends XXXServiceImpl {
    
    @Test
    public void xxxTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = this.getClass().getSuperclass().getDeclaredMethod("xxx", List.class, Set.class);
        method.setAccessible(true);
        Object o = method.invoke(this, Collections.singletonList("1111"), new HashSet<>());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/462002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号