【发布时间】:2017-12-15 04:45:57
【问题描述】:
我有一堂课,是这样的:-
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
}
}
}
任何帮助都非常感谢,在此先感谢。
【问题讨论】:
-
您是否可以控制示例中的类?如果是这样,那么您需要封装在您控制的抽象后面,然后模拟并注入到依赖类中。类还应该依赖于抽象,而不是具体或实现问题。
-
@Nkosi 你有什么例子吗?我是 .net 的新手。
标签: unit-testing mocking nunit moq sealed