简体   繁体   English

为什么 SonarQube 声称单元测试未涵盖“返回”行?

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

Here's my API endpoint:这是我的 API 端点:

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

And here is the SonarQube report:这是 SonarQube 报告:

在此处输入图片说明

The two green bars on lines 37 & 38 indicate that they are covered by the unit test.第 37 和 38 行上的两个绿色条表示它们已被单元测试覆盖。 But for some reason like 39 isn't?但出于某种原因,像 39 不是吗?

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 .您的Post方法返回一个int On your test you are expecting to receive a nullable int ( int? ).在您的测试中,您希望收到一个可为空的 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);我的猜测是问题在于,当您使用此断言时,您并没有真正测试方法的结果: 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.我想你的dashboardrepos.SaveSearchHistoryByUser方法应该返回你只是在你的数据库上保留的实体的主键。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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