无法传递 assertThrows,而是获取 java.lang.NoSuchMethodError

Can't pass assertThrows, instead get java.lang.NoSuchMethodError

我 honing/getting 我在 java 中做一些简单的代码挑战,并确保我可以断言代码何时运行以及何时抛出异常。

当我用应该通​​过的东西进行测试时,代码正确地通过了。当我让它抛出异常时,它就会抛出异常。 但是 当我对异常使用 assertThrows 时,测试失败并出现此错误:

java.lang.NoSuchMethodError: 'java.lang.Throwable org.junit.Assert.assertThrows(java.lang.Class, org.junit.function.ThrowingRunnable)'

测试代码如下:

package codeChallenges;

import org.junit.jupiter.api.Test;

import java.util.NoSuchElementException;

import static codeChallenges.TwoSum.twoSum;
import static org.junit.Assert.*;

public class TwoSumTest {

    @Test
    public void failingTwoSumTest() throws NoSuchElementException {
        Integer[] testArray = new Integer[2];
        Integer firstInt = 3;
        Integer secondInt = 7;
        testArray[0] = firstInt;
        testArray[1] = secondInt;
        assertThrows(NoSuchElementException.class, ()-> twoSum(testArray, 20));
    }

实际代码:

package codeChallenges;

import java.util.*;

public class TwoSum {
    public static int[] twoSum(Integer[] nums, int target) throws NoSuchElementException  {
        int[] solution = new int[]{-1, -1};
        HashMap<Integer, Integer> numMap= new HashMap<>(); 
        for (int i = 0; i < nums.length; i++) {
                int complement = target - nums[i];
                if (numMap.containsKey(complement)) {
                    solution[0] = i;
                    solution[1] = numMap.get(complement);
                    return solution;
                }
            numMap.put(nums[i], i);
            }
        throw new NoSuchElementException("a solution is not present");
    }
}

此处 are/is dependencies/build.gradle 文件:

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.6.1/userguide/java_library_plugin.html
 */

plugins {
    // Apply the java-library plugin to add support for Java Library
    id 'java-library'
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

dependencies {
    // This dependency is exported to consumers, that is to say found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:29.0-jre'
    implementation 'org.junit.jupiter:junit-jupiter:5.4.2'
    implementation 'org.junit.jupiter:junit-jupiter:5.4.2'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.13'
}

我已经使缓存失效并重新启动,我将代码从这个特定项目移到它自己的项目中...static 方法是否可运行会影响它吗?我在这里不知所措。预先感谢您的帮助。

assertThrows(NoSuchElementException.class, ()-> TwoSum.twoSum(testArray, 20));
    

您没有从 class 调用方法,而是试图直接调用,请改用 TwoSum.twoSum