我有一个班级,如下: -
namespace CalendarIntegration.Google
{
public sealed class GoogleSyncEventProcessor : ICalendarSyncEventProcessor
{
public void ProcessEventRequest(object events, int soUserId, string calendarId, bool addLogs = false)
{
if (GoogleWatchManager.Instance.IsGoogleTwoWaySynLive)
{
GoogleWatchManager是一个密封的类。
namespace CalendarIntegration.Google
{
public sealed class GoogleWatchManager
{
readonly bool isGoogleTwoWaySyncLive = true;
public GoogleWatchManager()
{
isGoogleTwoWaySyncLive = false;
}
virtual public bool IsGoogleTwoWaySynLive
{
get { return isGoogleTwoWaySyncLive; }
}
我想要伪造/模拟GoogleWatchManager类并在nunit测试用例中创建GoogleWatchManager.Instance.IsGoogleTwoWaySynLive
的值,默认情况下在GoogleWatchManager类中为true。
我尝试了以下但它不起作用 -
using EFBL;
using NUnit.Framework;
using EFBL.CalendarIntegration.CalendarSync;
using EFBL.CalendarIntegration.Google;
using Moq;
namespace EFBL.CalendarIntegration.Google
{
[TestFixture]
public class GoogleSyncEventProcessorSpec
{
public GoogleSyncEventProcessor google;
public GoogleWatchManager googleManager;
public void SetUp()
{
}
[Test]
public void ProcessEventRequest_NoEvents_ExceptionThrown()
{
var mock = new Mock<GoogleWatchManager>();
mock.SetupGet(foo => foo.IsGoogleTwoWaySynLive).Returns(true);
// watch.Setup(i => i.IsGoogleTwoWaySynLive).Returns(false);
// var mock = new Mock<GoogleWatchManager>().Object;
GoogleSyncEventProcessor obj = GoogleSyncEventProcessor.Instance;
obj.ProcessEventRequest(null, -1, "");
// isGoogleTwoWaySyncLive
}
}
}
任何帮助都非常感谢,提前感谢。
答案 0 :(得分:1)
以下是解决方案: -
using System;
using EFBL;
using NUnit.Framework;
using TypeMock.ArrangeActAssert;
using System.Diagnostics;
namespace EFBL.CalendarIntegration.Google
{
[TestFixture]
public class GoogleSyncEventProcessorSpec
{
public GoogleSyncEventProcessor googleSync;
public GoogleWatchManager googleManager;
[SetUp]
public void Init() {
googleManager = Isolate.Fake.Instance<GoogleWatchManager>();
googleSync = GoogleSyncEventProcessor.Instance;
}
[Test]
public void RequiresThatTwoWaySyncLiveBeFalse()
{
Isolate.NonPublic.Property.WhenGetCalled(googleManager, "IsGoogleTwoWaySynLive").WillReturn(false);
Assert.AreEqual(false, googleManager.IsGoogleTwoWaySynLive);
}
答案 1 :(得分:-1)
public sealed class GoogleWatchManager
我想要假冒/模拟GoogleWatchManager类[...]
Moq无法为sealed
类创建模拟。
以这种方式看待它:如果你想手动创建一个假的GoogleWatchManager
(即没有像Moq这样的模拟库),你会怎么做?
...(插入思考休息在这里)...
如果你不能自己动手,那么出于同样的原因,Moq可能会遇到同样的问题;毕竟,它只是自动完成你必须手动完成的任务,它没有任何特殊的权力。
首先,尝试删除sealed
关键字,以便创建一个覆盖属性getter的子类。