我正在尝试验证调用SetFirefoxOptions()
时是否调用了GetFirefoxDriver()
。但是无论出于什么原因,Moq一直告诉我没有被调用。我在做什么错了?
这是我的考试:
[TestMethod]
public void ShouldSetFirefoxOptions()
{
var stubCapabilities = new Mock<SauceCaps>().Object;
var mockManager = new Mock<DriverManager>();
mockManager.Setup(
m => m.GetFirefoxDriver(stubCapabilities)).
Returns(It.IsAny<IWebDriver>());
mockManager.Verify(
m => m.SetFirefoxOptions(stubCapabilities));
}
DriverManager.cs:
public class DriverManager : IDriverManager
{
public virtual Dictionary<string, object> SauceOptions { get; private set; }
public DriverManager()
{
}
public virtual IWebDriver GetFirefoxDriver(SauceCaps sauceCaps)
{
var browserOptions = SetFirefoxOptions(sauceCaps);
return new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
}
public virtual FirefoxOptions SetFirefoxOptions(SauceCaps sauceCaps)
{
return new FirefoxOptions
{
BrowserVersion = sauceCaps.BrowserVersion,
PlatformName = sauceCaps.Os
};
}
}
答案 0 :(得分:0)
您的代码存在的问题是,您不清楚受测系统是什么。您正在同时模拟和测试相同的类。尽管使用 moq
(使用CallBase)在技术上是可行的,但原则上是错误的方法。
一种可能性是将SetFirefoxOptions
提取到单独的interface
中,然后将其注入DriverManager
中,例如
public interface IFirefoxOptionCreator
{
FirefoxOptions SetFirefoxOptions(SauceCaps sauceCaps);
}
public DeviceManager(IFirefoxOptionCreator optionCreator)
{
_optionCreator = optionCreator;
}
public virtual IWebDriver GetFirefoxDriver(SauceCaps sauceCaps)
{
var browserOptions = _optionCreator.SetFirefoxOptions(sauceCaps);
return new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
}
然后您可以轻松地验证在单元测试中是否调用了接口方法:
[TestMethod]
public void ShouldSetFirefoxOptions()
{
// Arrange
var stubCapabilities = new Mock<SauceCaps>().Object;
var optionCreatorMock = new Mock<IFirefoxOptionCreator>();
optionCreatorMock.Setup(m => m.SetFirefoxOptions(It.IsAny<SauceCaps>()))
.Returns(new FirefoxOptions());
var sut = new DriverManager();
// Act
_ = sut.GetFirefoxDriver(stubCapabilities);
// Assert
optionCreatorMock.Verify(m => m.SetFirefoxOptions(stubCapabilities));
}