繁体   English   中英

验证对象在Rhino Mocks中调用自身

[英]Verify object calls itself in Rhino Mocks

如何将单元测试编写为以下代码:

public Image Get(BrowserName browser)
{
    // if no screenshot mode specified it means that regular screenshot needed
    return this.Get(browser, ScreenshotMode.Regular);
}

public Image Get(BrowserName browser, ScreenshotMode mode) {            
    // some code omitted here
}

通常这是通过部分模拟完成的,它们可能有点令人讨厌。

首先,您要模拟的方法必须是虚拟的。 否则Rhino Mocks无法拦截该方法。 因此,让我们将代码更改为:

public Image Get(BrowserName browser)
{
    // if no screenshot mode specified it means that regular screenshot needed
    return this.Get(browser, ScreenshotMode.Regular);
}

public virtual Image Get(BrowserName browser, ScreenshotMode mode) {            
    // some code omitted here
}

请注意,第二种方法现在是虚拟的。 然后,我们可以像这样设置部分模拟:

//Arrange
var yourClass = MockRepository.GeneratePartialMock<YourClass>();
var bn = new BrowserName();
yourClass.Expect(m => m.Get(bn, ScreenshotMode.Regular));

//Act
yourClass.Get(bn);

//Assert
yourClass.VerifyAllExpectations();

这就是AAA Rhino Mocks语法。 如果您喜欢使用记录/播放,也可以使用。


这就是您要执行的操作。 一个更好的解决方案是,如果ScreenshotMode是一个枚举并且您拥有C#4,只需将其设为可选参数即可:

public Image Get(BrowserName browser, ScreenshotMode mode = ScreenshotMode.Regular)
{
    //Omitted code.
}

现在您没有两种方法,因此无需测试一个调用另一个方法。

除了使方法成为虚拟方法外,还有两种可能性(如vcsjones所述):

1)

为模式为“常规”的Get(浏览器,模式)编写测试。 然后对Get(浏览器)运行相同的测试。

毕竟,两者都应返回完全相同的结果。

或2)

使用接口将第二个Get方法的代码提取到一个类中,并使其可注入经过测试的类中。 调用它:

public Image Get(BrowserName browser) {
  return whatever.Get(browser, ScreenshotMode.Regular);
}

public Image Get(BrowserName browser, ScreenshotMode mode) {   
  return whatever.Get(browser, mode);
}

现在,在测试过程中,您可以注入一个模拟并验证第一个Get方法使用ScreenshotMode.Regular调用它,而第二个Get方法仅将模式传递给它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM