我有一个使用这种方法的 asmx webserice
[WebMethod]
double GetBookPrice(int bookID)
{
//instantiates a DiscountService,DeliveryService and a couple of other services
//uses various methods of these services to calculate the price
//e.g. DiscountService.CalculateDiscount(book)
}
有 4 个服务是此方法的依赖项。
现在如何测试这个方法?我需要注入(inject)这些依赖项吗?或者我应该这样做吗?客户端只是发送一个整数来检查价格。
谢谢
请您参考如下方法:
如果 GetBookPrice 方法所做的只是获取一个 int 并将其传递给另一个方法,然后返回这些结果,我会说测试服务方法是具有可疑的值(value)。测试它不会有害,如果您想进一步扩展 GetBookPrice 方法中的功能,它可能会有值(value)。
不过,一般来说,如果您想测试您的服务,您会通过构造函数注入(inject)和构造函数链接来执行标准 IOC:
public class FooWebService
{
private readonly ISomeDependency dependency;
public FooWebService(ISomeDependency dependency)
{
//this is what you call during your testing
this.dependency = dependency;
}
public FooWebService() : this(new ConcreteDependencyImplementation())
{
}
}
当您进行测试时,您会传入一个依赖项(或多个依赖项!)的实例。当您不进行测试时,将通过调用无参数构造函数的方式自动创建和提供依赖项。
