在哪里放置取决于其他外部第三方服务的代码



我正在使用.NET中的存储库模式开发一个应用程序,作为我的业务逻辑的一部分,必须发送SMS。代码应该去哪里,以便在我的测试中实际上发送SMS?

外部互动,例如发送电子邮件,发送SMS,呼叫第三方Web服务等应该在业务层后面。您可以将它们视为与存储库的平行层。

业务层应负责与外部服务互动,但当然不是直接的。

应该有包装服务的书面服务,业务层应取决于包装器服务,而应取决于实际的外部端点。

考虑以下示例:

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");
    }
}

现在,您可以在不实际发送SMS的情况下进行单元测试订单服务。您需要创建对ISMSService和订单服务的其他依赖关系的模拟。

注意:上面的代码纯粹是一个示例。您可以对此有自己的想法,以使其满足您的特定需求。

这应该给您暗示如何安排图层并进行单位测试。

相关内容

最新更新