模拟没有setter的对象

时间:2016-02-09 17:46:01

标签: c# .net unit-testing moq

我正在使用第三方库 UserContext ,只有一堆{get;}

public static UserContext Current { get; }
public UserContact CurrentContact { get; }
public string UserContactName { get; }

在我的代码中,它只是像这样返回CurrentUser:

void DoSomething(){
    UserContext Current = UserContext.Current; // 3rd party lib
}

我无法为单元测试设置新的假对象。所以,为了在我的代码中模拟这个,我做了以下几点:

创建了一个继承自UserContext并覆盖Current属性的子类:

public class UserContextFake : UserContext
{
    public new UserContext Current { get; set; }
}

然后创建了一个接口和一个包装器:

public class UserContextWrapper : IUserContext
{
    public UserContextWrapper()
    {
        userContext = UserContext.Current;
    }

    public UserContextWrapper(UserContext context)
    {
        userContext = context;
    }

    private readonly UserContext userContext;

    public UserContext Current
    {
        get { return userContext; }
    }
}

现在我可以将userContextWrapper放入我的类中。我公开了两个构造函数:一个使用UserContext.Current(第三方库)会话的生产代码,以及可以接收自定义UserContextFake的构造函数。在IoC中,我将IUserContext映射到UserContext

问题:如果CurrentContact不在界面中,而且是UserContext的属性(UserContext.CurrentContact)

,我该如何模拟它?

1 个答案:

答案 0 :(得分:2)

你不能为整个3dr派对库创建一个界面吗?然后实现此接口并将此类用作第三方lib的包装器。方法。在被测试的班级中,然后添加例如可用于注入接口模拟的属性。示例(未经测试)。 HTH

public interface IThirdPartyLibraryWrapper
{
    UserContext Current { get; }
    UserContact CurrentContact { get; }
    string UserContactName { get; }
}

public class ThirdPartyLibraryWrapper 
    : IThirdPartyLibraryWrapper
{
    public UserContext Current 
    { 
        get { /* return Current from third party library */}
    }

    public UserContact CurrentContact 
    { 
        get{ /* return CurrentContact from third party library */} 
    }

    public string UserContactName 
    { 
        get{ /* return UserContactName from third party library */} 
    }
}

public class ClassUnderTest
{
    // Inject 3rd party lib
    private IThirdPartyLibraryWrapper _library;
    public virtual IThirdPartyLibraryWrapper Library
    {
        get
        {
            if (_library == null)
                _library = new ThirdPartyLibraryWrapper();
            return _library;
        }
        set
        {
            if (value != null)
                _library = value;
        }
    }

    void DoSomething(){
        UserContext Current = Library.Current; 
    }
}

[TestMethod]
public void DoSomething_WhenCalled_UsesLibraryMock()
{
    // Arrange
    UserContext fakeUserContext = new UserContext();
    Mock<IThirdPartyLibraryWrapper> libraryMock = new Mock<IThirdPartyLibraryWrapper>();
    libraryMock.Setup(l => l.Current).Returns(fakeUserContext);
    ClassUnderTest cut = new ClassUnderTest();
    cut.Library = libraryMock.Object;

    // Act
    cut.DoSomething()

    // Assert
    // ...
}