简体   繁体   中英

Unit test a method that returns a boolean

I have a method like this:

public bool CheckForRuleName(string ruleName, string studentId)
{
    var rules =
          _noSqlProvider.GetDocumentsByQuery<StudentRule>(string.Format(GET_Student_BASED_ON_RULENAME, ruleName, studentId));

    if (rules.Count() != 0)
    {
        return true;
    }
    return false;
}

Wrote a Unit test like so:

[TestMethod]
public void when_calling_CheckForRuleName_Should_Return_FALSE_WHEN_RULE_DOES_NOT_EXIST()
{
    var noSqlProv = new Mock<INoSqlProvider<Document, DocumentCollection>>();

    noSqlProv.Setup(x => x.GetDocumentsByQuery<StudentRule>(It.IsAny<string>()));

    var rulesRepository = new RulesRepository(noSqlProv.Object);
    bool rules = rulesRepository.CheckForRuleName("test123","testrule");

    Assert.AreEqual(false, rules);
}

The test is failing with the following exception:

ArgumentNullException: Value cannot be null.
Parameter name: source

Now the method GetDocumentsByQuery expects an SQL string like so:

"select j from json j where j.name='{0}' and j.studentid='{1}'"

It queries the DocumentDb, just to be complete on the question. Since it is not a good practice to a query the actual Db I used:

It.IsAny<string>()

I am new to unit testing so can someone please provide guidance on how to unit test this type of code.

Thanks in advance.

Regards.

Your stubbed method does not return any value so it defaults to returning null . Add a stub list of rules to the return clause. If you want it to return false, it would have to be an empty collection.

var stubbedRules = new StudentRule[0];
noSqlProv.Setup(x => x.GetDocumentsByQuery<StudentRule>(It.IsAny<string>())).Returns(stubbedRules);

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