无法传递assertthrows,而是获取java.lang.nosuchmethoderror

yv5phkfx  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(540)

我正在用java做一些简单的代码挑战,并确保在代码运行时和抛出异常时都能Assert。
当我用应该通过的东西进行测试时,代码会正确通过。当我让它抛出异常时,它抛出异常。但是当我在异常上使用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");
    }
}

下面是/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 是否可运行的影响?我在这里不知所措。提前谢谢你的帮助。

uhry853o

uhry853o1#

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

您不是从类中调用方法,而是试图直接调用,请改用twosum.twosum

相关问题