我正在使用.Net中的存储库模式开发一个应用程序,作为我的业务逻辑的一部分,必须发送SMS。这个代码应该放在哪里,以便在我的测试期间实际上不发送短信?
答案 0 :(得分:2)
发送电子邮件,发送短信,呼叫第三方网络服务等外部互动应该在业务层之后。您可以将它们视为存储库的并行层。
业务层应该负责与外部服务进行交互,但当然不是直接的。
应该写一个包装器服务,业务层应该依赖于包装器服务而不是实际的外部端点。
请考虑以下示例:
public interface ISmsService
{
bool SendSms(string toNumber, string messageBody);
}
public class TwilioSmsService : ISmsService
{
public bool SendSms(string toNumber, string messageBody)
{
// Send SMS using twilio
return true;
}
}
public interface ICustomerRepository
{
Customer GetCustomer(string customerId);
}
public class CustomerRepository : ICustomerRepository
{
public Customer GetCustomer(string customerId)
{
Expression<Func<Customer, bool>> criteria = cust => cust.CustomerId.Equals(customerId);
return return Context.Set<Customer>.FirstOrDefault(criteria);
}
}
public class OrderService
{
private IOrderRepository orderRepository;
private ISmsService smsService;
public ICustomerRepository customerRepository;
public OrderService(IOrderRepository orderRepository, ICustomerRepository customerRepository, ISmsService smsService)
{
this.orderRepository = orderRepository;
this.customerRepository = customerRepository;
this.smsService = smsService;
}
public void PlaceOrder(Order orderObj, string customerId)
{
this.orderRepository.SaveOrder(orderObj);
var customer = this.customerRepository.GetCustomer(customerId);
this.smsService.SendSms(customer.MobileNo, "You order is received successfully");
}
}
现在您可以在不实际发送短信的情况下对OrderService进行单元测试。您需要创建模拟ISmsService和OrderService的其他依赖项。
注意:上面的代码纯粹是一个例子。您可以对此有自己的想法,使其适合您的特定需求。
这应该为您提供有关如何安排图层和单元测试的提示。