简体   繁体   中英

Unit testing class

I'm doing unit testing with a class library and I'm stuck on how to test the method that need to test scenarios like check if a password with less than 8 characters cannot be accepted, check if a password with 8 or more characters can be accepted and check if a password with space in the front cannot be accepted.

The code below is from the class library.

public class PasswordChecker
{
    public bool CheckPassword(string pwd)
{
    if (pwd.Length >= 8 && !pwd.StartsWith(""))
    {
        return true;
    }
    else
    {
        return false;
    }
}
}

The code below is from the testing project.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using 12kiajunPA03;

namespace PasswordCheckerTest
{
[TestClass]
public class PasswordCheckerTest
{
    [TestMethod]
    public void Checkpassword()
    {
        string pwd = "1234qa1";

        Checkpassword password = new Checkpassword("John", pwd);

        try
        {

        }
        catch
        {

        }
    }
}

}

I imagine it would look something like this:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using 12kiajunPA03;

namespace PasswordCheckerTest
{
    [TestClass]
    public class PasswordCheckerTest
    {
        [TestMethod]
        public void Checkpassword8CharsLong()
        {
            string validPassword = "12345678";
            string invalidPassword = "abc";

            PasswordChecker checker = new PasswordChecker();

            Assert.IsTrue(checker.CheckPassword(validPassword));
            Assert.IsFalse(checker.CheckPassword(invalidPassword));
        }
    }
}

Using the same idea, you could write additional tests that check for other criteria that the passwords must meet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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