gpt4 book ai didi

c# - 使用 Moq 设置事件聚合器事件

转载 作者:行者123 更新时间:2023-11-30 21:41:23 26 4
gpt4 key购买 nike

我正在尝试对一个简单的方法进行单元测试,并验证某个事件是否已从该方法发布,但发现很难设置模型。

//Class under test
public class TreatmentRoomModel : ITreatmentRoomModel
{
public TreatmentRoomModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}

//Method under test
public void SetTreatmentInProgress(bool inProgress)
{
if (_isTreatmentInProgress == inProgress) return;
_isTreatmentInProgress = inProgress;

_eventAggregator.Publish(new TreatmentStatus(_isTreatmentInProgress), Execute.OnUIThread);
}
}

//TreatmentStatus event
public class TreatmentStatus
{
public TreatmentStatus(bool isInProgress)
{
IsInProgress = isInProgress;
}

public bool IsInProgress { get; private set; }
}

我正在尝试测试方法 SetTreatmentInProgress 并验证 eventaggregator 正在发布正确的 TreatmentStatus 事件。事件聚合器是 typeof(Caliburn.Micro.IEventAggregator)

下面是测试设置

 [TestClass]
public class TreatmentRoomModelTests
{
private Mock<IEventAggregator> _mockEventAggregator;
ITreatmentRoomModel _treatmentRoomModel;

private readonly TreatmentStatus _treatmentInProgressEvent = new TreatmentStatus(true);
private readonly TreatmentStatus _treatmentNotInProgressEvent = new TreatmentStatus(false);

[TestInitialize]
public void Initialize()
{
_mockEventAggregator = new Mock<IEventAggregator>();

//I am not sure how to set the property IsInProgress of TreatmentStatus to true? It is a privately set property through constructor.
_mockEventAggregator.Setup(x => x.Publish(It.IsAny<TreatmentStatus>(), Execute.OnUIThread));

//Or should I directly publish a true event, but then how to verify the event object without a reference to it.
//_mockEventAggregator.Setup(x => x.Publish(new TreatmentStatus(true), Execute.OnUIThread));


_treatmentRoomModel = new TreatmentRoomModel(_mockEventAggregator.Object);
}

[TestMethod]
public void SetTreatmentInProgressTest()
{
_treatmentRoomModel.SetTreatmentInProgress(true);

//This works, but I wan't to verify that the object of TreatmentStatus event has the property IsInProgress set to true.
_mockEventAggregator.Verify(x=>x.Publish(It.IsAny<TreatmentStatus>(), Execute.OnUIThread),Times.Once);


_treatmentRoomModel.SetTreatmentInProgress(false);

//Won't work, as it says this is getting called Times.None. I understand this may be because of different TreatmentStatus objects, which are raised and verified.
_mockEventAggregator.Verify(x=>x.Publish(new TreatmentStatus(false), Execute.OnUIThread),Times.Once);

}
}

最佳答案

修复表达式以使用 It.Is<>

//This works, but I wan't to verify that the object of TreatmentStatus event has the property IsInProgress set to true.
_mockEventAggregator
.Verify(x=>x.Publish(It.Is<TreatmentStatus>(_ => _.IsInProgress == true), Execute.OnUIThread),Times.Once);

关于c# - 使用 Moq 设置事件聚合器事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391920/

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