首页 > 解决方案 > 尝试进行 JUnit 测试但遇到一些错误

问题描述

下面是 JUnit 测试器类

import java.lang.reflect.Method;

public class SimpleUnitTester {

    public int execute(Class clazz) throws Exception {
        int failedCount = 0;

        // your code
        
        execute(Reflection.class);
        Reflection reflection = null;
        
        try {
            reflection = (Reflection) clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        Method[] methods = clazz.getDeclaredMethods();
        
        for (Method method : methods) {
            if (method.getName().startsWith("test") && method.getReturnType() == boolean.class) {
                
                try {                                       
                    boolean returnedValue = ((Boolean) method.invoke(reflection)).booleanValue();

                    if (!returnedValue) {
                        failedCount++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        }

        return failedCount;
    }
}

下面是反射类

public class Reflection {
   public void go() {
   }
   public boolean testA() {
       return true;
   }   
   public void foo() {     
   }
   public void bar() {     
   }
   public int testB() {
       return 0;
   } 
   public boolean testC() {
       return false;
   }
   public boolean testD() {
       return false;
   }
   public boolean testE() {
       return true;
   }
   public boolean anotherTest() {
       return false;
   }
}

我想做类似的测试,在反射类中,如果方法以关键字“test”开头并且如果方法具有布尔返回类型,那么它将使测试合格。如果测试失败,则返回测试失败值。但是我在 Output 中得到了 Null

标签: javajunit

解决方案


推荐阅读