繁体   English   中英

JavaFx MediaPlayer 在单元测试与应用程序中的行为不同,为什么?

[英]JavaFx MediaPlayer behaves differently in unit test vs application, why?

我想从 MP3 文件加载元数据,由 JavaFx MediaPlayer 播放。 这在单元测试中可以正常工作,但在应用程序中却不行。 在单元测试中,报告了 6 项元数据,但在应用程序中为零。 “做事”的方法是一样的。

应用程序的主要 class 扩展了应用程序。 测试 class 扩展了来自 TestFx 的 ApplicationTest。 这会影响行为吗?

应用程序:

public class MediaMain extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        Map<String, Object> meta = metaData();

        System.out.printf("Number of meta data: %d.%n", meta.size());
        System.out.println(meta);
    }

    Map<String, Object> metaData() {
        File audioFile = new File("src/main/resources", "beingBoiled.mp3");
        final URI uri = audioFile.toURI();
        final String source = uri.toString();
        Media media = new Media(source);
        new MediaPlayer(media);
        return media.getMetadata();
    }
}

单元测试:

class MediaMainTest extends ApplicationTest {

    @Test
    void testMeta() {
        MediaMain main = new MediaMain();

        Map<String, Object> metaData = main.metaData();

        assertNotEquals(0, metaData.size());
        System.out.printf("Number of meta data: %d.%n", metaData.size());
        System.out.println(metaData);
    }
}

从应用程序打印输出:

Number of meta data: 0.
{}

单元测试的打印输出:

Number of meta data: 6.
{year=1980, artist=The Human League, raw metadata={ID3=java.nio.HeapByteBufferR[pos=254 lim=3214 cap=3214]}, album=Travelogue, genre=(52), title=Being Boiled}

可能是什么原因? 这对我来说是个谜。 使用 Java 11、JavaFx 11.0.2 和 TestFx 4.0.15-alpha 编写。

您正在引用位置为src/main/resources的文件,这可能不是一个好主意,因为您部署的应用程序可能没有src/main/resources目录,而且资源可能捆绑在应用程序 jar 中,而不是而不是作为磁盘上的文件,因此使用文件协议访问它是行不通的。

最好使用以下内容:

String mediaLoc = getClass().getResource("/beingBoiled.mp3").toExternalForm()
Media media = new Media(mediaLoc)

就像 如何在 javafx8 中加载 css 文件一样 要加载的资源的确切位置可能因构建和项目结构而异。 如果您不想从 class 路径加载,而是通过文件或通过网络 http 调用加载,那么您将需要使用其他东西。

The above code assumes that your build system is setup to copy the media from the src/main/resources to your target packaging location and package the resource into the application distributable (eg an application jar file) in the root of the jar file.

确保您的构建系统实际上正在将文件复制到目标位置。 You can check if it is there by running your build, looking at the resultant jar and running jar tvf <myjarfilename>.jar to see if the mp3 resource is in the correct location at the root of the jar file.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM