【问题标题】:Why I cannot use expected in JUnit 4为什么我不能在 JUnit 4 中使用预期
【发布时间】:2019-04-17 22:26:56
【问题描述】:

我正在尝试测试负责从文件中检索数据的方法。 我想测试是否正确抛出异常。

   package contentfile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ContentFileRetrieverService implements ContentFileRetriever {

    @Override
    public String[] getContentFile(String pathName) {

        Stream<String> contentFileStream;
        try {
            contentFileStream = Files.lines(Paths.get(pathName));
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        return contentFileStream.toArray(String[]::new);
    }
}

我的测试:

package contentfile;

import org.junit.jupiter.api.Test;

import static org.junit.Assert.*;

class ContentFileRetrieverServiceTest {

    private ContentFileRetrieverService contentFileRetrieverService = new ContentFileRetrieverService();

    @Test
    void getContentFile() {
        String pathFile = "src\\test\\java\\resources\\TestText.txt";
        String[] testedContent = contentFileRetrieverService.getContentFile(pathFile);
        String[] expected = {"Line1 a", "Line2 b c", "Line 3"};
        assertArrayEquals(expected, testedContent);
    }

    @Test(expected =  IllegalArgumentException.class)
    void getContentFileWhenFileDoesNotExist() {
        String pathFile = "unknown";
        String[] testedContent = contentFileRetrieverService.getContentFile(pathFile);
    }
}

pom,xml

<dependency>

    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

它无法编译,因为它无法解析方法excepted 我做错了什么? PS: 你能告诉我我是否用这两种方法正确测试了这个方法吗?

【问题讨论】:

  • 属性名为"expected";你拼错了。
  • @rgettman 抱歉,这是意料之中的。我重写它并立即犯这个错误。即使我写@Test(expected = IllegalArgumentException.class),它仍然不起作用

标签: java unit-testing junit


【解决方案1】:

您正在混合使用 JUnit 4 和 JUnit 5。

expected 元素存在于 JUnit4 @Test

JUnit 5 提供了更强大的 assertThrows 代替

【讨论】:

  • 但是我对 &lt;version&gt;4.12&lt;/version&gt; 有依赖,那么我如何与 JUnit 5 混合?
  • 可能你不仅有这个依赖。也许您的 IDE 提供了一个...您的测试类导入来自 JUnit5 的 org.junit.jupiter.api.Test 和来自 JUnit 4 的 org.junit.Assert。尝试查找对 org.junit.jupiter 组工件的依赖项
  • 我添加了编辑并粘贴了 pom.xml 的版本。可以看看吗?
  • 是的,junit-jupiter-api 是对 JUnit5 的依赖。因此,您可以删除对 JUnit4 的依赖并采用 Assertions.assertThrows... 或坚持使用 JUnit4 并使用 org.junit.Test 而不是 org.junit.jupiter.api.Test
猜你喜欢
  • 2021-10-30
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多