-
Notifications
You must be signed in to change notification settings - Fork 345
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Documentation on writing unit tests for Actors that access state #1169
Comments
https://github.com/dapr/dotnet-sdk/blob/3b979e6bdb1d779563f1656fa684183b2bfecd08/test/Dapr.Actors.Test/ITestActor.cs#L47C31-L47C31 implements overriding of the StateManager by providing an optional IStateManager parameter in the constructor. If that is provided, |
@jaq316 is this a recommendation to provide an |
In case it's useful to anyone else, my approach to this was as follows: internal class TestUserStateActor : UserStateActor
{
private Dictionary<string, UserState> _state = [];
public static TestUserStateActor CreateTestActor()
{
var actorHost = ActorHost.CreateForTest<UserStateActor>();
return new TestUserStateActor(actorHost);
}
private TestUserStateActor(ActorHost host) : base(host)
{
Mock<IActorStateManager> mockStateManager = new();
mockStateManager
.Setup(m => m.SetStateAsync(It.IsAny<string>(), It.IsAny<UserState>(), default))
.Callback((string key, UserState value, CancellationToken _) => _state[key] = value);
mockStateManager
.Setup(m => m.GetStateAsync<UserState>(It.IsAny<string>(), default))
.ReturnsAsync((string key, CancellationToken _) => _state[key]);
mockStateManager
.Setup(m => m.TryGetStateAsync<UserState>(It.IsAny<string>(), default))
.ReturnsAsync((string key, CancellationToken _) =>
{
if (_state.TryGetValue(key, out UserState? value))
{
return new ConditionalValue<UserState>(true, value);
}
return new ConditionalValue<UserState>();
});
mockStateManager
.Setup(m => m.ContainsStateAsync(It.IsAny<string>(), default))
.ReturnsAsync((string key, CancellationToken _) => _state.ContainsKey(key));
StateManager = mockStateManager.Object;
}
} |
Documentation on writing unit tests, specifically for Actors accessing state would be great.
The below code, for instance, would throw: "InvalidOperationException: The actor was initialized without a state provider, and so cannot interact with state. If this is inside a unit test, replace Actor.StateProvider with a mock."
The text was updated successfully, but these errors were encountered: