gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:05:07 24 4
gpt4 key购买 nike

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

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.
}

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

关于c# - 验证对象在 Rhino Mocks 中调用自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com