簡體   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