1
public class MyClass: AbstractBase
{
    public override bool Init(IAppContext contextIn)
    {
        if (base.Init(contextIn))
        {
            //my code 
        }
    }
}

我有一个上面给出的类,想为 Init 方法编写一个单元测试,并模拟了IAppContext. 如何使用 mock 绕过对 base 的调用?

这就是我正在做的事情:

Mock<IAppContext> mockContex = new Mock<IAppContext >();
MyClass myClassInstance - new MyClass ();
myClassInstance.Init(mockContex.object);

base.init看起来像:

public virtual bool Init(IAppContext context_in) 
{
    if (context_in == null)
    {
        throw new ArgumentNullException("context_in", "IAppContext argument s null"); 
    } 
    this.myCommunication = context_in.getInterface<ICommunication>();
    if (this.myCommunication == null)
    { 
        throw new ArgumentNullException("myCommunication", "ICommunication argument is null");
    } 
    this.myStateManager = new IStateManager(this.myCommunication);
    if (this.myStateManager == null)
    { 
        throw new InvalidOperationException("Could not create the State Manager");
    }
    return true; 
} 
4

1 回答 1

1

您可以以返回 trueIAppContext的方式设置您的模拟:base.Init

var communicationFake = new Mock<ICommunication>();
var appContextMock = new Mock<IAppContext>();

appContextMock
    .Setup(c => c.getInterface<ICommunication>())
    .Returns(communicationFake.Object);

现在base.Inittrue在使用 调用时返回appContextMock

请注意,您不需要最后一次 null 检查 ( ) -失败this.myStateManager == null的唯一方法是抛出异常。new IStateManager(this.myCommunication)如果是这样,它无论如何都不会进入空检查部分。

于 2012-05-09T08:17:59.707 回答