C# 在Rhino模拟中验证对象调用自身
如何将单元测试写入以下代码:C# 在Rhino模拟中验证对象调用自身,c#,.net,unit-testing,rhino-mocks,C#,.net,Unit Testing,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)
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 Mock无法拦截该方法。因此,让我们将代码更改为:
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();
现在您没有两个方法,因此不需要测试一个方法调用另一个方法。这通常是通过部分模拟完成的,它们可能有点令人讨厌 首先,您模拟的方法必须是虚拟的。否则Rhino Mock无法拦截该方法。因此,让我们将代码更改为:
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();
现在您没有两个方法,因此无需测试一个方法调用另一个方法。除了使方法虚拟化之外,还有两种可能性(如vcsjones所解释的): (一) 使用常规模式编写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);
}
现在,在测试过程中,您可以插入一个mock,并验证第一个Get方法是否使用ScreenshotMode.Regular调用它,而第二个Get方法只是将该模式传递给用户。除了使方法虚拟之外,还有两种可能性(如vcsjones解释的): (一) 使用常规模式编写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);
}
现在,在测试过程中,您可以插入一个mock,并验证第一个Get方法是否使用ScreenshotMode.Regular调用它,而第二个Get方法只是传递模式。为什么不让它调用公共私有方法?为什么不让它调用公共私有方法?