【发布时间】:2012-01-29 14:17:52
【问题描述】:
我想用FakeItEasy 测试以下(此处为简化)代码。
public class ActionExecutor : IActionExecutor
{
public void TransactionalExecutionOf(Action action)
{
try
{
// ...
action();
// ...
}
catch
{
// ...
Rollback();
}
}
public void Commit()
{ }
public void Rollback()
{ }
}
public class Service : IService
{
private readonly IRepository _repository;
private readonly IActionExecutor _actionExecutor;
// ctor for CI
public void ServiceMethod(string name)
{
_actionExecutor.TransactionalExecutionOf(() =>
{
var item = _repository.FindByName(ItemSpecs.FindByNameSpec(name));
if (item == null) throw new ServiceException("Item not found");
item.DoSomething();
_actionExecutor.Commit();
}
}
}
我想测试 ServiceException 是否被抛出,所以我这样设置我的测试
var repo = A.Fake<IRepository>();
A.CallTo(() => repo.FindByName(A<ISpec<Item>>.Ignored))
.Returns(null);
var executor = A.Fake<IActionExecutor>();
executor.Configure()
.CallsTo(x => x.Rollback()).DoesNothing();
executor.Configure()
.CallsTo(x => x.Commit()).DoesNothing();
executor.Configure()
.CallsTo(x => x.TransactionalExecutionOf(A<Action>.Ignored))
.CallsBaseMethod();
使用以下代码
var service = new Service(executor, repo);
service.ServiceMethod("notExists")
.Throws(new ServiceException());
我收到以下消息
当前代理生成器无法拦截指定方法 原因如下: - 密封方法不能被拦截。
如果我直接在服务上调用方法
var service = new Service(executor, repo);
service.ServiceMethod("NotExists");
我收到这条消息
这是一个 DynamicProxy2 错误:拦截器试图“继续” 对于方法 'Void TransactionalExecutionOf(System.Action)' 没有 目标。调用没有目标的方法时没有实现 “继续”,拦截器有责任 模仿实现(设置返回值,输出参数等)
现在有点迷茫,不知道接下来该怎么办。
【问题讨论】:
标签: c#-4.0 action fakeiteasy