为什么我不能在 JUnit 4 中使用 expected

pip*_*lam 3 java junit unit-testing

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

   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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

它不会编译,因为它无法解决excepted我做错的方法?PS:你能告诉我用这两种方法测试这个方法是否正确?

cac*_*co3 7

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

expected元素存在于 JUnit4 中@Test

JUnit的5个报价更加强大assertThrows,而不是