实体类自动化测试用例

参考:https://blog.csdn.net/jdzms23/article/details/17550119


import org.testng.annotations.Test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.*;

public class BeanAutoTest {

    private List getPackageList() {
        List packageList = new ArrayList<>();
        packageList.add("com.test.dto");
        packageList.add("com.test.vo");
        packageList.add("com.test.entity");
        return packageList;
    }


    @Test
    public void test() {
        List packageList = getPackageList();

        for (String packageName : packageList) {
            Set> classes = getClasses(packageName);
            for (Class clazz : classes) {
                autoTest(clazz);
            }
        }
    }


    public static Set> getClasses(String packageName) {
        Set> classes = new HashSet<>();

        try {
            String packageDirName = packageName.replace('.', '/');
            Enumeration urls = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件,并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, true, classes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }


    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, boolean recursive, Set> classes) {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }

        // 获取包下的所有文件,包括目录
        File[] dirFiles = dir.listFiles(new FileFilter() {
            // 自定义过滤规则: 目录(迭代) 或 以.class结尾的文件
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });

        if (null != dirFiles) {
            // 循环所有文件
            for (File file : dirFiles) {
                // 如果是目录 则继续扫描
                if (file.isDirectory()) {
                    String subPackageName = packageName + "." + file.getName();
                    findAndAddClassesInPackageByFile(subPackageName, file.getAbsolutePath(), recursive, classes);
                } else {
                    // 如果以.class结尾的文件,只留下类名
                    String className = file.getName().substring(0, file.getName().length() - 6);
                    try {
                        classes.add(Class.forName(packageName + '.' + className));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    private void autoTest(Class clazz) {
        try {
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                Object obj = clazz.newInstance();
                String name = method.getName();
                if (name.startsWith("set")) {
                    // set方法调用
                    Class[] parameterTypes = method.getParameterTypes();
                    // 只调用拥有唯一参数的set方法
                    if (parameterTypes.length == 1) {
                        Class parameterType = parameterTypes[0];
                        if (parameterType == String.class) {
                            method.invoke(obj, "");
                        } else if (parameterType == BigInteger.class) {
                            method.invoke(obj, BigInteger.valueOf(123));
                        } else if (parameterType == BigDecimal.class) {
                            method.invoke(obj, BigDecimal.valueOf(123));
                        } else if (parameterType == int.class || parameterType == Integer.class) {
                            method.invoke(obj, 123);
                        } else if (parameterType == short.class || parameterType == Short.class) {
                            method.invoke(obj, (short) 123);
                        } else if (parameterType == long.class || parameterType == Long.class) {
                            method.invoke(obj, 123L);
                        } else if (parameterType == double.class || parameterType == Double.class) {
                            method.invoke(obj, 123.123D);
                        } else if (parameterType == Date.class) {
                            method.invoke(obj, new Date());
                        } else if (parameterType == List.class) {
                            method.invoke(obj, new ArrayList());
                        } else if (parameterType == boolean.class || parameterType == Boolean.class) {
                            method.invoke(obj, true);
                        } else if (parameterType == Map.class) {
                            method.invoke(obj, new HashMap());
                        } else if (parameterType == Set.class) {
                            method.invoke(obj, new HashSet());
                        } else if (parameterType == Timestamp.class) {
                            method.invoke(obj, Timestamp.valueOf("2019-11-02 12:00:00"));
                        } else if (parameterType == String[].class) {
                            method.invoke(obj, new Object[1]);
                        } else if (parameterType == int[].class || parameterType == Integer[].class) {
                            method.invoke(obj, new Object[1]);
                        } else {
                            method.invoke(obj, parameterType.newInstance());
                        }
                    }
                } else if (name.startsWith("get")) {
                    // get方法调用
                    Class[] cls = method.getParameterTypes();
                    // 只调用无参数的get方法
                    if (cls.length == 0) {
                        method.invoke(obj);
                    }
                }
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

 

                            
                        
                    
                    
                    

你可能感兴趣的:(实体类自动化测试用例)