Dav*_*idS 2 captcha unit-testing common-library fluentvalidation fakeiteasy
我正在使用commonlibrary中的Captcha类(http://commonlibrarynet.codeplex.com/).我的代码工作和一切,但现在我正在尝试编写单元测试.
我的验证规则是:
RuleFor(x => x.CaptchaUserInput)
.NotEmpty()
.Must((x, captchaUserInput) => Captcha.IsCorrect(captchaUserInput, x.CaptchaGeneratedText))
.WithMessage("Invalid captcha code");
Run Code Online (Sandbox Code Playgroud)
在我的设置代码中,我尝试执行以下操作:
A.CallTo(() => Captcha.IsCorrect()).Returns(true);
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误消息:
SetUp : FakeItEasy.Configuration.FakeConfigurationException :
The current proxy generator can not intercept the specified method for the following reason:
- Static methods can not be intercepted.
at FakeItEasy.Configuration.DefaultInterceptionAsserter.AssertThatMethodCanBeInterceptedOnInstance(Metho dInfo method, Object callTarget)
at FakeItEasy.Configuration.FakeConfigurationManager.CallTo(Expression`1 callSpecification)
at ProdMaster.Hosts.Web.Tests.Unit.Controllers.AccountControllerTests.SetUp() in AccountControllerTests.cs: line 44
Run Code Online (Sandbox Code Playgroud)
所以问题实际上是如何使用FakeItEasy伪造静态方法.
TIA,
大卫
在FakeItEasy中无法拦截静态方法(目前没有其他开源,.Net的免费模拟框架).为了能够模拟静态(和密封类),您必须从Telerik购买Typemock Isolator或Just Mock.
许多开发人员认为静态是代码气味(在大多数情况下).因此,开源模拟框架不支持这一事实被视为一件好事,因为它促进了更好的设计.模拟的"黄金法则"是"如果你无法控制它就不要嘲笑它",所以解决你遇到的问题的常见方法是在静态调用周围创建一个包装器.你测试与这个 - mockable - 包装器的交互.System.DateTime.Now是您经常要在测试中测试的静态示例.要将测试与此隔离,您可以执行以下操作:
public interface ISystemTimeProvider
{
DateTime Now { get; }
}
public class DateTimeNowSystemTimeProvider
: ISystemTimeProvider
{
public DateTime Now
{
get
{
return DateTime.Now;
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的接口和实现,您的SUT将取决于接口(例如通过构造函数注入).在你的测试中,你会用假(A.Fake<ISystemTimeProvider>())注入它.DateTimeSystemTimeProvider的实现永远不会进行单元测试,它的级别非常低,除了集成测试之外不需要任何其他测试.
我对你正在谈论的验证码库不是很熟悉,所以我不确定在这种情况下你将如何应用上述模式,但我确信它可以通过这种或那种方式完成.
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |