Skip to content

Commit

Permalink
match behaviors of mocked and real data repositories (#356)
Browse files Browse the repository at this point in the history
  • Loading branch information
makp0 authored Apr 23, 2021
1 parent 75fdf78 commit a2240a7
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/Fakes/NetDaemon.Fakes/RxAppMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Reactive.Linq;
using Microsoft.Reactive.Testing;
using Newtonsoft.Json;

namespace NetDaemon.Daemon.Fakes
{
Expand Down Expand Up @@ -37,7 +38,7 @@ public class RxAppMock : Mock<INetDaemonRxApp>
/// </summary>
public TestScheduler TestScheduler { get; } = new();

private readonly IDictionary<string, object> _mockDataRepository = new Dictionary<string, object>();
private readonly IDictionary<string, string> _mockDataRepository = new Dictionary<string, string>();

/// <summary>
/// Default constructor
Expand Down Expand Up @@ -165,10 +166,24 @@ public RxAppMock()
});

Setup(s => s.SaveData(It.IsAny<string>(), It.IsAny<object>()))
.Callback<string, object>((id, data) => _mockDataRepository.Add(id, data));
.Callback<string, object>((id, data) =>
{
if (_mockDataRepository.ContainsKey(id))
{
_mockDataRepository.Remove(id);
}

_mockDataRepository.Add(id, JsonConvert.SerializeObject(data));
});

Setup(s => s.GetData<object>(It.IsAny<string>()))
.Returns<string>(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)
Expand Down
27 changes: 27 additions & 0 deletions tests/NetDaemon.Daemon.Tests/FakesTests/RxMockTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TestData>(id);

// ASSERT
Assert.NotNull(updatedTestData);
Assert.Equal(updatedTestData.Value, savedObject!.Value);
}

private class TestData
{
public string? Value { get; init; }
Expand Down

0 comments on commit a2240a7

Please sign in to comment.