我正在使用Hangfire安排一些工作。我的所有工作都有一个计划日期,所以我使用Schedule静态扩展方法
public static string Schedule([NotNull] this IBackgroundJobClient client, [InstantHandle][NotNull] Expression<Action> methodCall, DateTimeOffset enqueueAt);
我想对我的方法进行单元测试,以便我可以检查Hangfire是否实际被触发。
为此,我遵循了Hangfire关于单元测试的文档(https://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html),该文档建议模拟IBackgroundJobClient
并验证它具有的唯一公共Create方法:
string Create([NotNull] Job job, [NotNull] IState state);
但我可以看到,对于Schedule调用,这没有被调用,而是另一个不公开的重载被调用,所以我得到以下错误:
Message: Moq.MockException :
Expected invocation on the mock at least once, but was never performed: x => x.Create(It.IsAny<job>(), It.IsAny<enqueuedstate>())
No setups configured.
Performed invocations:
IBackgroundJobClient.Create(JobService.TaskFunction, ScheduledState)
尽管如此,我已经尝试使用Enqueue
方法,这似乎适用于模拟。但我需要使用Schedule
。
另一个选择是断言它实际上正在调用
public static string Create([NotNull] this IBackgroundJobClient client, [InstantHandle][NotNull] Expression<Action> methodCall, [NotNull] IState state);
但由于它是一种扩展方法,因此对于Moq而言,这不是一种有效的方法。
Message: System.NotSupportedException : Invalid verify on an extension method: x => x.Create(It.IsAny<Expression<Action>>(), It.IsAny<EnqueuedState>())
那么我怎样才能为Schedule
方法测试Hangfire?
你引用的例子使用不同的扩展方法,最后调用不同的IBackgroundJobClient
方法,github。已调用以下方法:
client.Create(Expression<Action> methodCall, new EnqueuedState());
它完全符合示例中的Verify
。
另一方面,你正在调用Schedule
方法,github。最后的Schedule
方法调用以下内容:
client.Create(Expression<Action> methodCall, new ScheduledState(enqueueAt.UtcDateTime))
这也是一种表达方法,因此您需要深入了解更多级别,其中调用了实际的interface
方法:
string Create([NotNull] Job job, [NotNull] IState state);
从错误本身可以看出,您的期望与实际调用不匹配:
Performed invocations:
IBackgroundJobClient.Create(JobService.TaskFunction, ScheduledState)
你的断言应该是这样的:
// Assert
client.Verify(x => x.Create(
It.IsAny<Job>(), //you could as in example check actual method name
It.IsAny<IState>()); //you could check actual offset