gpt4 book ai didi

c# - 单元测试 ReactiveUI View 模型和命令

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:37 25 4
gpt4 key购买 nike

我有一个使用 ReactiveUI 实现的工作 View ,现在我正在尝试为我的 View 模型编写一些单元测试,但我的 View 模型在测试中使用时似乎不起作用。

具体来说,执行命令似乎不会触发订阅者。在下面的这个测试中,我正在调用 AddPlayer 命令,但订阅的处理程序没有运行:

public class NewGameViewModelTests
{
private NewGameViewModel viewmodel;

public NewGameViewModelTests()
{
viewmodel = new NewGameViewModel();
}

[Fact]
public void CanAddUpToSevenPlayers()
{
foreach(var i in Enumerable.Range(1, 7))
{
viewmodel.NewPlayerName = "Player" + i;
viewmodel.AddPlayer.Execute(null);
Assert.Equal(i, viewmodel.Players.Count);
}
}
}

这是我正在测试的 View 模型:

public class NewGameViewModel : ReactiveObject
{
public ReactiveList<string> Players { get; private set; }
public ReactiveCommand<Object> AddPlayer { get; private set; }
public ReactiveCommand<Object> RemovePlayer { get; private set; }
public ReactiveCommand<Object> StartGame { get; private set; }
public ReactiveCommand<Object> RandomizeOrder { get; private set; }


string newPlayerName;
public string NewPlayerName {
get { return newPlayerName; }
set { this.RaiseAndSetIfChanged(ref newPlayerName, value); }
}

public NewGameViewModel()
{
Players = new ReactiveList<string> ();

var canStart = this.Players.CountChanged.Select(count => count >= 3);
StartGame = canStart.ToCommand();
RandomizeOrder = canStart.ToCommand();

RemovePlayer = ReactiveCommand.Create();
AddPlayer = this.WhenAnyValue(x => x.Players.Count, x => x.NewPlayerName,
(count, newPlayerName) => count < 7 && !string.IsNullOrWhiteSpace(newPlayerName) && !this.Players.Contains(newPlayerName))
.ToCommand();

RandomizeOrder.Subscribe(_ =>
{
using (Players.SuppressChangeNotifications())
{
var r = new Random();
var newOrder = Players.OrderBy(x => r.NextDouble()).ToList();
Players.Clear();
Players.AddRange(newOrder);
}
});

RemovePlayer.Subscribe(player =>
{
this.Players.Remove((string)player);
});

AddPlayer.Subscribe(_ =>
{
Players.Add(NewPlayerName.Trim());
NewPlayerName = string.Empty;
});
}
}

最佳答案

在我的机器上似乎没有失败,使用 ReactiveUI master。也许发生了其他事情?

编辑:这是带有 Xamarin.Forms 的 ReactiveUI 中的错误,要解决它,请将其添加到在测试运行开始时运行的某个位置:

RxApp.MainThreadScheduler = Scheduler.CurrentThread;

关于c# - 单元测试 ReactiveUI View 模型和命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25357303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com