Unity3d JsonUtility.FromJson()从TextAsset中读取的数据在应用程序中有效,在测试运行器中失败。

问题描述 投票:-1回答:1

以下代码在我的应用程序(Unity 2019.3.0f6)中工作正常。它从AssetsResourceslesson-text.json读取并将预期的日志写入控制台。

// file to read lessons from
public TextAsset jsonFile;

 internal JsonLessonList LoadLessonFromFile()
{
    JsonLessonList testLessonList = JsonUtility.FromJson<JsonLessonList>(jsonFile.text);

    foreach (JsonLesson lesson in testLessonList.jsonLessonList)
    {
        Debug.Log("Found lesson: " + lesson.Name);
    }

    return testLessonList;
}

我想在使用Unity的测试运行器时,读取同样的文件。

    [UnityTest]
    public IEnumerator TestFileParsesOkTest()
    {
        JsonLessonList testLessonList = jsonReader.LoadLessonFromFile();
        Assert.IsNotNull(testLessonList);

        yield return null;
    }

但我一直得到这个异常。

TestFileParsesOkTest (0.019s)

未处理的日志消息。'[异常]NullReferenceException。Object reference not set to an instance of an object'. 使用 UnityEngine.TestTools.LogAssert.Expect

JsonReader.LoadLessonFromFile()(在AssetsScriptsJsonReader.cs:68)。

JsonReader.Start() (在AssetsScriptsJsonReader.cs:37)

NullReferenceException。对象引用未设置为对象的实例。

我知道文件格式没问题,因为从应用中可以看到。 我认为问题在于通过unity编辑器设置的 "TextAsset jsonFile "没有被Test Runner看到。 如何让这个问题解决?

    [Test]
    public void JsonFileResourceTest()
    {
        Assert.IsNotNull(jsonReader.jsonFile);
    }

结果是

JsonFileResourceTest (0.020s)

预期:不为零 但曾经:为零

(测试驱动开发的标签是因为我拿到了一个最简单的读取文件,其中有一个字段是可以用的,现在我想备份并为它写一个单元测试,然后再写测试,然后再继续编码)。

unity3d tdd test-runner
1个回答
0
投票

我想明白了。

[SetUp]
public void Setup()
{
    jsonReader = new GameObject().AddComponent<JsonReader>();
    jsonReader.jsonFile = Resources.Load("lesson-test") as TextAsset;
}

// Verify class exists
[Test]
public void JsonReaderClassExists()
{
    Assert.IsNotNull(jsonReader);
    Assert.IsNotNull(jsonReader.jsonFile);
}
© www.soinside.com 2019 - 2024. All rights reserved.