我有一个使用ReactiveUI实现的工作视图,现在我正在尝试为我的视图模型编写一些单元测试,但是我的视图模型在测试中使用时似乎不起作用。
具体来说,执行命令似乎不会触发订阅者。在下面的测试中,我正在调用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);
}
}
}
以下是我正在测试的视图模型:
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;
});
}
}
答案 0 :(得分:6)
使用ReactiveUI master在我的机器上似乎没有失败。也许其他事情正在发生?
编辑:这是ReactiveUI中使用Xamarin.Forms的一个错误,要解决此问题,请将其添加到测试运行开始时运行的地方:
RxApp.MainThreadScheduler = Scheduler.CurrentThread;