From a2240a71781f5f1ec3a2970a17876218dae79bd5 Mon Sep 17 00:00:00 2001 From: Zorgino Date: Fri, 23 Apr 2021 13:09:46 +0300 Subject: [PATCH] match behaviors of mocked and real data repositories (#356) --- src/Fakes/NetDaemon.Fakes/RxAppMock.cs | 21 ++++++++++++--- .../FakesTests/RxMockTests.cs | 27 +++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/Fakes/NetDaemon.Fakes/RxAppMock.cs b/src/Fakes/NetDaemon.Fakes/RxAppMock.cs index 0cf9f66fd..76180b98d 100644 --- a/src/Fakes/NetDaemon.Fakes/RxAppMock.cs +++ b/src/Fakes/NetDaemon.Fakes/RxAppMock.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Reactive.Linq; using Microsoft.Reactive.Testing; +using Newtonsoft.Json; namespace NetDaemon.Daemon.Fakes { @@ -37,7 +38,7 @@ public class RxAppMock : Mock /// public TestScheduler TestScheduler { get; } = new(); - private readonly IDictionary _mockDataRepository = new Dictionary(); + private readonly IDictionary _mockDataRepository = new Dictionary(); /// /// Default constructor @@ -165,10 +166,24 @@ public RxAppMock() }); Setup(s => s.SaveData(It.IsAny(), It.IsAny())) - .Callback((id, data) => _mockDataRepository.Add(id, data)); + .Callback((id, data) => + { + if (_mockDataRepository.ContainsKey(id)) + { + _mockDataRepository.Remove(id); + } + + _mockDataRepository.Add(id, JsonConvert.SerializeObject(data)); + }); Setup(s => s.GetData(It.IsAny())) - .Returns(id => _mockDataRepository.TryGetValue(id, out var value) ? value : null); + .Returns(new InvocationFunc(invocation => + { + var id = (string)invocation.Arguments[0]; + var returnType = invocation.Method.GetGenericArguments()[0]; + + return _mockDataRepository.TryGetValue(id, out var value) ? JsonConvert.DeserializeObject(value, returnType) : null; + })); } private void UpdateMockState(string[] entityIds, string newState, object? attributes) diff --git a/tests/NetDaemon.Daemon.Tests/FakesTests/RxMockTests.cs b/tests/NetDaemon.Daemon.Tests/FakesTests/RxMockTests.cs index fb0d02ed5..4a1226394 100644 --- a/tests/NetDaemon.Daemon.Tests/FakesTests/RxMockTests.cs +++ b/tests/NetDaemon.Daemon.Tests/FakesTests/RxMockTests.cs @@ -380,6 +380,33 @@ public void TestSaveAndGetData() Assert.Equal(testData.Value, savedObject!.Value); } + [Fact] + public void TestSaveOverridesExistingData() + { + // ARRANGE + const string id = "id"; + + var testData = new TestData() + { + Value = "test_value" + }; + + var updatedTestData = new TestData() + { + Value = "updated_test_value" + }; + + // ACT + Object.SaveData(id, testData); + Object.SaveData(id, updatedTestData); + + var savedObject = Object.GetData(id); + + // ASSERT + Assert.NotNull(updatedTestData); + Assert.Equal(updatedTestData.Value, savedObject!.Value); + } + private class TestData { public string? Value { get; init; }