业务代码HubService中新增了一个方法,HubService使用ABP框架注入到依赖它的服务中:

public async Task RequestOrderAddress(string targetClientId, string orderId)
{
	// 读取一个订单,并对订单做后续逻辑的处理
	var esOrderData = await _thirdPartOrderProvider.GetThirdPartOrderAsync(grainId.ToString());
	if (esOrderData == null)
	{
		_logger.LogError("This order {OrderId} not exists in the es", orderId);
		break;
	}
	
    // address not callback yet
    if (string.IsNullOrWhiteSpace(esOrderData.Address))
    {
   		// 没有订单地址的情况
   		
   		return;
	}
	
	// 有订单地址的情况
	
	...

}

 

为了在单测中覆盖有地址和没地址两种情况需要mock GetThirdPartOrderAsync 方法返回的订单数据,

测试类是继承自 AbpIntegratedTest 的,AbpIntegratedTest中提供了一个后置方法,可以在注入完成之后对已有的服务做修改,

 


    protected override void AfterAddApplication(IServiceCollection services)
    {
    	// 调用GetThirdPartOrderProvider方法获取一个mock的服务,mock的服务会根据不同的条件返回不同的数据
        services.AddSingleton(GetThirdPartOrderProvider());
    }
    
    // 返回一个Mock的服务实例,根据不同条件返回不同的对象
    private IThirdPartOrderProvider GetThirdPartOrderProvider()
    {
        var mockProvider = new Mock<IThirdPartOrderProvider>();

		// 订单对象1
        var noAddressData = new OrderDto
        {
            Id = new Guid("00000000-0000-0000-0000-000000000001"),
        };

		// 订单对象2
        var withAddressData = new OrderDto
        {
            Id = new Guid("00000000-0000-0000-0000-000000000002"),
            Address = "123456"
        };
        
        // 根据订单ID返回不同的订单对象
        mockProvider.Setup(provider => provider.GetThirdPartOrderAsync(It.Is<string>(id => id == "00000000-0000-0000-0000-000000000001"))).ReturnsAsync(noAddressData);
        mockProvider.Setup(provider => provider.GetThirdPartOrderAsync(It.Is<string>(id => id == "00000000-0000-0000-0000-000000000002"))).ReturnsAsync(withAddressData);

        return mockProvider.Object;
    }
    
    // 测试的方法
    [Fact]
    public async void RequestOrderAddressTest()
    {
    	// 用两个不同的orderId对应的订单数据测试不同的case
        await _hubService.RequestOrderAddress("123", "00000000-0000-0000-0000-000000000001");
        await _hubService.RequestOrderAddress("123", "00000000-0000-0000-0000-000000000002");
    }