xUnit-Test中的模拟异步方法始终返回null

问题描述 投票:1回答:1

我有一个ASP.NET WebAPI 2项目,我正在尝试使用xunit和moq添加单元测试。

这是我的控制器中的Get-Method:

public class SiteController : ApiController
{
    private readonly ISite _siteSrv;

    public SiteController( ISite siteSrv )
    {
        _siteSrv = siteSrv;
    }

    public async Task<IHttpActionResult> Get( int id )
    {
        //reading current user login id and user roles [...]

        // getting data from SiteService, which I try to mock
        var site = await _siteSrv.Get( id, userLoginId.Value, roles );

        //converting it into a model [...]

        return Ok(model);
    }
}

和我的SiteService的Get方法:

public async Task<Site> Get( int id, long userLoginId, string[] roles )
{
    //...doing some stuff
    // and returning the data
    return await _context.Sites
        .AsNoTracking()
        .FirstOrDefaultAsync( s => s.SiteId == id );
}

这是我的测试方法:

[Fact]
public async Task Verify_GetId_Method_Returns_OkResult_ForAdmin()
{
    int siteId = 1;
    long userLoginId = 1;
    string role = "Admin";

    // fake site
    var site = new Site()
    {
        SiteId = 1,
        SiteName = "Site1"
    };

    // mocking the SiteService
    var mockSite = new Mock<ISite>();
    // setting up the Get-Method returning the fake site asynchronously
    mockSite.Setup( s => s.Get( siteId, userLoginId, new string[] { role } ) )
        .ReturnsAsync( site );

    // faking HttpContext
    using ( new FakeHttpContext.FakeHttpContext() )
    {
        // current logged in user
        HttpContext.Current.User = CurrentUserTestData.GetAccount( 
            userLoginId, role );

        // the SiteController with the mocked SiteService
        var controller = new SiteController( mockSite.Object );
        // setting Request
        controller.Request = new HttpRequestMessage();
        controller.Request.Properties.Add( 
            HttpPropertyKeys.HttpConfigurationKey,
            new HttpConfiguration() );

        // calling the async Get method of the controller
        var result = await controller.Get( siteId );
        // !! result is always NULL !!

        Assert.NotNull( result ); // FAIL
    }
}

知道我在做什么错吗?

unit-testing async-await asp.net-web-api2 moq xunit
1个回答
1
投票

因此问题是参数匹配器正在查看您的参数,并试图将其与Setup中提供的参数匹配。它通过使用默认的相等性(对于数组意味着引用相等性)来做到这一点。因此,对于string[]个角色,您将不匹配该参数,并且Setup将永远不匹配,并且您将获得空结果。更改设置以允许任何角色阵列都将使匹配器成功。

mockSite.Setup( s => s.Get( siteId, userLoginId, It.IsAny<string[]>() ) )
    .ReturnsAsync( site );
© www.soinside.com 2019 - 2024. All rights reserved.