Masriyah
Masriyah

Reputation: 2525

How to write a C# unit test in Visual Studio?

This is my first unit test and wanted some help clearing out my thoughts about the process of writing a unit test.

I wanted to write a test method that will add a new user - using my AddUser method in my library class.

Document doc = new Document();

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

The error I am getting on build:

Cannot implicitly convert type void to string

This is my AddUser method:

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

Upvotes: 5

Views: 1566

Answers (5)

Murali Gangineni
Murali Gangineni

Reputation: 83

Make sure you return the name from from your AddUser(string newUserName) method.

Replace your method like

public String AddUser(string newUserName)
{
    using (var db = new DataContext())
    {
        User user = new User()
        {
            FullName = newUserName,
            ID = Guid.NewGuid()
        };
        db.Users.InsertOnSubmit(user);
        db.SubmitChanges();
    }
    return newUserName;
}

Upvotes: 2

Harry89pl
Harry89pl

Reputation: 2435

Simply speaking you can't assign void to string.

To make it work you can do in 2 ways: make your method AddUser return string type or add extra parameter to your method and use keyword out for this parameter

hope it help.

Upvotes: 0

Dave Swersky
Dave Swersky

Reputation: 34820

AddUser is written as a method, not a class. Your test attempts to call it like a method, but the method is void, which does not return a value.

Upvotes: 0

mellamokb
mellamokb

Reputation: 56779

Your method does not have a return value:

public void AddUser
       ^^^^ no return value

So you can't store it into a string:

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

Upvotes: 12

Daniel A. White
Daniel A. White

Reputation: 191048

AddUser doesn't return anything.

Upvotes: 0

Related Questions