我对ReactiveTest的使用感到有点困惑:https://msdn.microsoft.com/en-us/library/hh242967%28v=vs.103%29.aspx
我在类DeviceService中有一个方法ScanDevices,我想用ReactiveTest功能进行测试。
该方法从bleAdapter.Scan()
获取IObservable。
我想模仿这个bleAdapter.Scan(),对ScanDevices()
的行为进行单元测试。我尝试用Moq模拟bleAdapter.Scan()。
//interface to mock
public interface IAdapter {
IObservable<IScanResult> Scan(ScanConfig config = null);
}
//class to test
class DeviceService {
public IObservable<DeviceModel> ScanDevices()
{
return bleAdapter.Scan() // this returns an IObservable
.Where(IsMatching)
.Distinct(DistinctByUuid)
.Select(ToDeviceModel);
}
}
这是我的单元测试:
public class DeviceServiceTest: ReactiveTest {
[TestMethod]
public void ShouldReceiveOneDevice()
{
var mockBleAdapter = new Mock<IAdapter>();
var deviceInteractionService = new DeviceInteractionService(mockBleAdapter.Object);
var scheduler = new TestScheduler();
var obs = scheduler.CreateColdObservable(OnNext(100, new MockScannedDevice())); // create an observable that will emit one value
mockBleAdapter.Setup(adapter => adapter.Scan(null))
.Returns(obs); // use Moq framework to return the observable created
scheduler.Start();
deviceInteractionService.ScanDevices()
.Subscribe(res => Console.WriteLine("hello"));
}
}
&#34;你好&#34;永远不会打印。我做错了...... 你有什么好办法吗?
由于
答案 0 :(得分:1)
唉......问题是你需要在致电scheduler.Start()
所以,要打印你好的问候,这里是:
public class DeviceServiceTest: ReactiveTest {
[TestMethod]
public void ShouldReceiveOneDevice()
{
var mockBleAdapter = new Mock<IAdapter>();
var deviceInteractionService = new DeviceInteractionService(mockBleAdapter.Object);
var scheduler = new TestScheduler();
var obs = scheduler.CreateColdObservable(OnNext(100, new MockScannedDevice())); // create an observable that will emit one value
mockBleAdapter.Setup(adapter => adapter.Scan(null))
.Returns(obs); // use Moq framework to return the observable created
// subscribe
deviceInteractionService.ScanDevices()
.Subscribe(res => Console.WriteLine("hello"));
// then start
scheduler.Start();
}
}