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

现在我有一个操作,它调用了我在服务层中定义的某个方法,我在服务层中使用了以下代码行.

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

现在我如何为这个创建单元测试方法,我得到了空引用异常.我对编写单元测试之类的东西有点陌生.

我只想为此使用单元测试.请帮我解决这个问题.

推荐答案

下面的方法只是一种:

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

Asp.net相关问答推荐

单个方法(即扩展方法)之间的调用不明确

VS2012 中无法识别的标签前缀或设备过滤器asp

ReportViewer 控件 - 高度问题

IIS Request.UserHostAddress 返回 IPV6 (::1),即使禁用了 IPV6

使用会话变量有多安全 - asp.net / c#

ASP.NET GridView 第二个标题行跨越主标题行

使用 jQuery 验证插件匹配两个字段

Asp.Net 会话在 ashx 文件中为空

使用 IIS 的 ASP.NET 调试超时

我应该使用用户名还是用户 ID 来引用 ASP.NET 中经过身份验证的用户

没有回发的按钮?

使用 Visual Studio 2012 恢复删除的文件

带有完整内存错误的 WCF 服务(内存门判断失败,因为可用内存) - 如何解决

跟踪点有什么用途?

在 JavaScript 中获取当前会话值?

远程计算机无法连接到 Visual Studio Web 服务器

如何将我的 Autofac 容器插入 ASP. NET 身份 2.1

asp.net core 2.0 - 值不能为空.参数名称:连接字符串

为什么 Controls 集合不提供所有 IEnumerable 方法?

如何在服务器控件属性中使用 ASP.NET <%= 标签?