c# - 如何在 Visual Studio 中编写 C# 单元测试?

标签 c# asp.net-mvc unit-testing

这是我的第一个单元测试,需要一些帮助来理清我对编写单元测试过程的想法。

我想编写一个添加新用户的测试方法 - 在我的库类中使用我的 AddUser 方法。

Document doc = new Document();

[TestMethod]
public string AddUser()
{
    string name = doc.AddUser("Testing User");
    Assert.IsNotNull(name);
}

我在构建时遇到的错误:

Cannot implicitly convert type void to string

这是我的 AddUser 方法:

public void AddUser(string newUserName)
{
    using (var db = new DataContext())
    {
        User user = new User()
        {
            FullName = newUserName,
            ID = Guid.NewGuid()
        };

        db.Users.InsertOnSubmit(user);
        db.SubmitChanges();
    }
}

最佳答案

您的方法没有返回值:

public void AddUser
       ^^^^ no return value

所以你不能把它存储成一个字符串:

string name = doc.AddUser("Testing User");
^^^^^^^^^^^ AddUser has no return value

关于c# - 如何在 Visual Studio 中编写 C# 单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363744/

相关文章:

c# - 直接从 Razor View 调用 Controller 操作方法

asp.net - 单元测试 Web 服务 - HttpContext

unit-testing - 处理程序单元测试的模拟功能

C# 使用 LINQ 从结构列表中提取 ID

c# - 不同年份格式的正则表达式 c#

c# - Controller 没有收到从表单返回的所有属性

c# - 为什么当我从 C#.net 中的不同变量中删除时它从其他变量中删除?

java - 单元测试 : finding class dependencies

c# - 通过 .NET 确定每个查询的 DocumentDB 请求费用

c# - 从 ASP.Net MVC5 调用的单独类库 .dll 中的 Hangfire