diff --git a/AppDataStorage.Test/AppDataTests.cs b/AppDataStorage.Test/AppDataTests.cs index 675b40e..b147f03 100644 --- a/AppDataStorage.Test/AppDataTests.cs +++ b/AppDataStorage.Test/AppDataTests.cs @@ -366,6 +366,20 @@ public void TestLoadOrCreateHandlesCorruptFile() Assert.AreEqual(string.Empty, appData.Data, "Data should be default if loaded from corrupt file."); } + [TestMethod] + public void TestLoadOrCreateHandlesNullJsonFile() + { + AbsoluteFilePath filePath = TestAppData.Get().FilePath; + AppData.EnsureDirectoryExists(filePath); + AppData.FileSystem.File.WriteAllText(filePath, "null"); + + TestAppData appData = TestAppData.LoadOrCreate(); + + AssertAppDataNotNull(appData, "LoadOrCreate should recover if file deserializes to null."); + Assert.AreEqual(string.Empty, appData.Data, "Data should be default if loaded from a null json file."); + Assert.IsTrue(AppData.FileSystem.File.Exists(filePath), "Recovery should recreate a valid settings file."); + } + [TestMethod] public async Task TestMultipleSavesOnlyWriteOnceWithinDebouncePeriod() { diff --git a/AppDataStorage/AppData.cs b/AppDataStorage/AppData.cs index df19e06..9eeaa5f 100644 --- a/AppDataStorage/AppData.cs +++ b/AppDataStorage/AppData.cs @@ -515,7 +515,8 @@ public static T LoadOrCreate(RelativeDirectoryPath? subdirectory, FileName? file try { - newAppData = JsonSerializer.Deserialize(jsonString, AppData.JsonSerializerOptions)!; + newAppData = JsonSerializer.Deserialize(jsonString, AppData.JsonSerializerOptions) + ?? throw new JsonException("Deserialized settings file to null."); newAppData.Subdirectory = subdirectory; newAppData.FileNameOverride = fileName; return newAppData;