简体   繁体   English

使用Moq和MS测试进行单元测试

[英]Unit testing with moq and ms test

I am new to this stuff and I read about test but I can't figure it out how to test this function : 我是这个东西的新手,我读了有关test的文章,但我不知道如何测试此功能:

   [Authorize(Roles = "admin")]
    [Route("user/byUsername/{username}")]
    public async Task<IHttpActionResult> GetUserByName(string username)
    {
        var user = await this.AppUserManager.FindByNameAsync(username);

        if (user != null)
        {
            return Ok(this.TheModelFactory.Create(user));
        }

        return NotFound();

    }

I want to use Moq and MS Test.Thank you. 我想使用Moq和MS Test。谢谢。

You have to paths in your method, so both can to be tested to have full coverage. 您必须在方法中使用路径,因此可以对两者进行测试以具有完整的覆盖范围。 Assumed the AppUserManager is injected into the class with di you are able to create a mock version of it that returns a null on the method FindByNameAsync(username), or a user. 假设将AppUserManager用di注入到类中,则可以创建它的模拟版本,该模拟版本在方法FindByNameAsync(username)或用户上返回null。 The Assert will test the NotFound and the returned Ok with content. 声明将测试NotFound和返回的Ok内容。

You would also be able to write a test to check if the attributes are present and have the correct content. 您还可以编写测试以检查属性是否存在并具有正确的内容。 That will guard you against typos and unexpected changes in the route or roles. 这样可以防止输入错误和路线或角色发生意外更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM