gpt4 book ai didi

java - JUnit:当测试的类不包含方法时,类方法的测试会中断编译

转载 作者:行者123 更新时间:2023-11-30 10:11:39 28 4
gpt4 key购买 nike

构建 JUnit 测试类。它被用作自动分级机。一些提交没有所有必需的类方法(即使它是规范的一部分)。 Autograder 当然只是总成绩的一部分(比如 50%)。它改进了玩 500 场游戏的问题,以测试它们是否按预期运行。

除了检查所有方法是否存在之外,最好检查它们是否也可调用。

JUnit 测试代码片段:

@Test
public void test_1p1t4_15() {
// Test if callable
try {
Direction d1 = new Direction();
checkMethod(d1.getClass(), "print");
} catch (Exception e) {
fail("Test fails:"+e.toString());
}
}

checkMethod 函数有助于显示问题何时与方法的实现相关,例如可见性,例如

public void checkMethod( Class cls, String fnName) {
// Checks method validity for methods not including an argument
try {
Method m = cls.getMethod(fnName);
assertNotNull(m);
} catch (Exception e) {
fail("Failed: "+e.toString());
}
}
public void checkMethod( Class cls, String fnName, Class type) {
// Checks method validity for methods including an argument
try {
Method m = cls.getMethod(fnName, type);
assertNotNull(m);
} catch (Exception e) {
fail("Failed: "+e.toString());
}
}
public void testMethod( Class cls, String fnName) {
// Code here
}
public void testMethod( Class cls, String fnName, argType, argValue) {
// Code here
// Including an argument
}

最佳答案

这是一个简单的示例,演示了如何查找和调用带参数的方法(如果该方法存在)。您需要在 JUnit 测试中调用 invokeIfExists。然后您将能够断言返回的值与您期望的值匹配。

import java.lang.reflect.*;

public class Main {

static Object invokeIfExists(Class<?> cls, String methodName,
Class<?>[] argTypes,
Object callingObject, Object[] args) {
try {
Method method = cls.getDeclaredMethod(methodName, argTypes);
return method.invoke(callingObject, args);
} catch (SecurityException | NoSuchMethodException e) {
System.err.println("Method " + methodName + " not found.");
} catch (IllegalAccessException | IllegalArgumentException e) {
System.err.println("Method " + methodName + " could not be invoked.");
} catch (InvocationTargetException e) {
System.err.println("Method " + methodName + " threw an exception.");
}
return null; // Or assert false, etc.
}

public static void main(String[] args) {
Direction direction = new Direction("a", "b");

// Tries to invoke "direction.print(123)"
String printResult = (String) invokeIfExists(
Direction.class, "print", new Class<?>[]{int.class},
direction, new Object[]{123});
System.out.println(printResult); // "Direction: a -> b and foo=123"

// Tries to invoke "direction.doesntExist()"
Object doesntExistResult = invokeIfExists(
Direction.class, "doesntExist", new Class<?>[]{},
direction, new Object[]{});
System.out.println(doesntExistResult); // null
}
}

class Direction {
private String from, to;

Direction(String from, String to) {
this.from = from;
this.to = to;
}

String print(int foo) {
return "Direction: " + from + " -> " + to + " and foo=" + foo;
}
}

关于java - JUnit:当测试的类不包含方法时,类方法的测试会中断编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com