【发布时间】:2014-05-21 09:42:00
【问题描述】:
假设我们有我想测试的PaymentService:
public interface IPaymentService
{
int Pay(int clientId);
}
public class PaymentService : IPaymentService
{
// Insert payment and return PaymentID
public int Pay(int clientId)
{
int storeId = StaticContext.Store.CurrentStoreId; // throws NullReferenceException
// ... other related tasks
}
}
public class Payment_Tests
{
[Test]
public void When_Paying_Should_Return_PaymentId
{
// Arrange
var paymentServiceMock = new Mock<IPaymentService>();
paymentService.Setup(x=>x.Pay(Moq.It.IsAny<int>).Returns(999); // fails because of NullReferenceException inside Pay method.
// Act
var result = paymentService.Object.Pay(123);
// Asserts and rest of the test goes here
}
}
但我无法模拟 StaticContext 类。 我无法重构这个并通过构造函数将这个类注入到IPaymentService - 这是旧代码,必须保持不变:(
是否有可能简单地返回预期结果,在我的情况下为 999 而无需调用底层 StaticContext.Store.CurrentStoreId?
编辑:我知道目前这个测试没有意义,但我想知道是否有办法以我要求的方式做到这一点。这只是我的问题的简化版本。
【问题讨论】:
-
那时,您认为您实际上会测试什么?如果你模拟了
IPaymentService,你就不是在测试PaymentService... -
看起来你在模拟运动。你想在这里测试什么?
-
是的,但这只是我的问题的简化版本。我真正的 PaymentService 用于我的代码的其他部分。我只想跳过支付方式。
-
如果你试图做一个部分模拟(这就是它的样子),这表明你需要将你的班级分成另一个班级
-
StaticContext 是静态类吗?如果是,Moq 不能模拟静态类或静态方法。
标签: c# unit-testing tdd moq