1
如果接口實現中使用的事件沒有出現在您正在模擬的接口中,是否有單元測試用moq引發事件的方法?使用Moq來測試不在接口中的事件
注意:我的界面與我的UI沒有任何關係,我的事件僅用於UI通知,所以我想將該行爲與實際界面分離,因爲存儲庫位於客戶端的單獨庫中/ UI。
例如:
[Test]
public void TestRaiseBarProcessed()
{
ManualResetEvent barProcessedEvent = new ManualResetEvent(false);
bool called = false;
//Arrange
Mock<IFooRepository> mockFooRepository = new Mock<IFooRepository>();
mockSourceRepository
.Setup(a => a.SearchForBar(barsToFind))
.Returns(barsFound)
.Raises(
a => a.BarProcessed += null,
new BarFoundEventArgs(It.IsAny<string>()));
IList<IFooRepository> mockFooRepositories =
new List<IFooRepository>();
mockFooRepositories.Add(mockFooRepository.Object);
FooBar fooBar = new FooBar(mockFooRepositories, FooList);
fooBar.CurrentBarBeingProcessedInfo += (sender, e) =>
{
barProcessedEvent.Set();
called = true;
};
//Act
fooBar.CallFooRepositoryMethod();
barProcessedEvent.WaitOne(25, false);
//Assert
mockFooRepository.Verify(
a => a.SearchForBar(barsToFind),
Times.Once());
Assert.AreEqual(true, called);
}
讓我知道是否有這個需要更多的澄清。
謝謝,我甚至沒有想到這個選擇。 – NexAddo
如果實現這兩個接口的類被迭代:「foreach(fooRepos中的IFooRepository回購){(IBarUIEvent)(回購).BarProcessed + = barProcessed; }'在這個例子中你如何測試? – NexAddo
@NexAddo:你的代碼示例很混亂。您在foreach中訂閱由枚舉器返回的實例?如果是這樣,你需要模擬'fooRepos'(確切地說,'GetEnumerator'方法)來返回'IFooRepository'的模擬版本,並且對這些模擬執行'Setup'。 –