简体   繁体   中英

Why does SonarQube claim the `return` line is not covered by a unit test?

Here's my API endpoint:

[HttpPost]
public int Post(SearchHistory searchHistory)
{
    IDashboardRepository dashboardrepos = new DashboardRepository();
    int historyId = dashboardrepos.SaveSearchHistoryByUser(searchHistory);
    return historyId;
}

And here is the SonarQube report:

在此处输入图片说明

The two green bars on lines 37 & 38 indicate that they are covered by the unit test. But for some reason like 39 isn't?

Here's the test:

[TestMethod()]
public void GlobalSeach_PutTest()
{
    SearchHistory history = new SearchHistory {
        // redacted for ease of reading on SO
    }
    var controller = new GlobalSearchController(_config);
    int? response = controller.Post(history);
    Assert.IsTrue(response != null);
}

Your Post method returns an int . On your test you are expecting to receive a nullable int ( int? ).

My gues is the problem is that your are not really testing the result of your method when you use this assert: Assert.IsTrue(response != null); . The first problem is that kind of test will never fail.

I imagine that your dashboardrepos.SaveSearchHistoryByUser method should return the primary key of the entity you just persist on your db. Based on that assumption I suggest you to refactoring your test as I describe below, to improve and solve the problem with coverage.

[TestMethod()]
public void GlobalSeach_PutTest()
{
    SearchHistory history = new SearchHistory {
        // redacted for ease of reading on SO
    }

    // _dashboardreposMock is an example of Mock<IDashboardRepository>
    _dashboardreposMock.Setup(_ => _.SaveSearchHistoryByUser(It.IsAny<SearchHistory>)).Returns(1);

    var controller = new GlobalSearchController(_config);
    int response = controller.Post(history);
    Assert.IsTrue(response == 1);
}

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