写单元测试使用User.Identity.Name中的ASP.NET Web API方法 [英] Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API

查看:323
本文介绍了写单元测试使用User.Identity.Name中的ASP.NET Web API方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在用的单元测试的ASP.NET Web API编写测试用例。

I am writing test cases using the Unit Test for ASP.NET Web API.

现在我有一个动作,这使得调用我在服务层定义了一些方法,在那里我已经使用了code以下行。

Now I have an action which makes a call to some method I have defined in the service layer, where I have used the following line of code.

string username = User.Identity.Name;
// do something with username
// return something

现在怎么我这个创建单元测试方法,我得到空引用异常。我还挺新编写单元测试之类的东西。

Now how to I create unit test method for this, I am getting null reference exceptions. I am kinda new to writing unit test and stuff.

和我想要使用单元测试只是这一点。

And I want to use Unit Test only for this.

请帮我出这一点。谢谢你。

Please help me out on this. Thanks.

推荐答案

下面一个是这样做的只有一个办法:

The below one is only one way of doing this:

public class FooController : ApiController {

    public string Get() {

        return User.Identity.Name;
    }
}

public class FooTest {

    [Fact]
    public void Foo() {

        var identity = new GenericIdentity("tugberk");
        Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
        var controller = new FooController();

        Assert.Equal(controller.Get(), identity.Name);
    }
}

这篇关于写单元测试使用User.Identity.Name中的ASP.NET Web API方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆