📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does SonarQube (or SonarQube Cloud) fit into a .NET team's pipeline? Explain quality gates, the 'new code' focus, which edition you need for pull request analysis, and how you stop the team from gaming the metrics.

Covers how SonarQube Server and SonarQube Cloud analyse .NET code with the scanner, how quality gates and the new-code period work, edition differences for branch and pull request analysis, coverage import, and how to avoid metric gaming.

Intermediate Theory Intermediate ci-cd code-coverage code-quality quality-gates sonarqube static-analysis

🎯 Key points

  • dotnet-sonarscanner begin / dotnet build / dotnet test / end: the scanner hooks the Roslyn build, so analysis needs a real build inside the CI pipeline
  • Quality gate = pass/fail conditions on a branch or PR, made a required PR check; default 'Sonar way' targets new code: no new issues, hotspots reviewed, coverage on new code ≥ 80%, duplication ≤ 3%
  • New code definition (previous version, number of days, reference branch) makes the gate about what you changed: 'Clean as You Code'
  • Coverage is imported, not measured: coverlet or dotnet-coverage output via sonar.cs.opencover / vscoveragexml reportsPaths
  • Community Build (named Community Edition before late 2024) analyses only the main branch; branch and PR analysis with PR decoration needs Developer Edition or above, or SonarQube Cloud
  • Gaming: tests without asserts for coverage, bulk 'Accept' (formerly Won't fix) resolutions, wide exclusions; counter with review of resolutions, mutation testing, few meaningful gate conditions
  • Read metrics as trends: reliability and security ratings, duplication and debt estimates start conversations; they are not targets (Goodhart's law)

⏱ 30-second answer

SonarQube runs in CI: the dotnet-sonarscanner wraps your build (begin → dotnet build → dotnet test → end), collects Roslyn analyser results plus imported coverage, and the server stores issues over time.

A quality gate is a set of pass/fail conditions. The default Sonar way gate looks only at new code: no new issues, every new security hotspot reviewed, at least 80% coverage on new lines, at most 3% duplication. The new code period (previous version, N days or a reference branch) is what makes legacy code adoptable: you don't fix the past, you stop making it worse.

The Community Build only analyses the main branch; pull request decoration needs Developer Edition or above, or SonarQube Cloud.

Trade-off: gates focus attention, but once a number becomes a target people game it (assert-free tests, bulk Won't fix), so keep few conditions and review how issues are resolved.

🗣 Full answer (senior)

How I would answer this in an interview

"SonarQube is a platform on top of static analysis. For C# it uses its own Roslyn analysers, so in the pipeline you run dotnet sonarscanner begin, then the normal dotnet build and dotnet test with coverage, then dotnet sonarscanner end, which uploads everything. The server keeps the history: every issue, when it appeared, who resolved it and how. Coverage isn't measured by Sonar; you produce an OpenCover or Visual Studio coverage file with coverlet or dotnet-coverage and point the scanner at it.

The part that matters most is the quality gate and the new code focus. A quality gate is a list of conditions that turns the analysis into a pass or fail, and you make that a required check on the pull request. The default gate is about new code: no new issues, new security hotspots reviewed, 80% coverage on changed lines, low duplication. 'New code' is defined per project, usually as changes since the previous version or compared with the main branch. That's what makes it usable on a ten-year-old codebase: nobody has to fix 6,000 old issues, but every PR has to leave the code it touches clean. Editions matter here. The free Community Build only analyses the main branch, so you can't gate pull requests; branch and PR analysis with decoration starts at Developer Edition, and SonarQube Cloud includes it.

The mistake I see is managing by the dashboard: a manager sets 'coverage must reach 85%' and soon there are tests that call methods with no asserts, and issues bulk-marked Won't fix. I keep the gate to a few conditions the team agreed, I review resolutions in the PR, and I treat the numbers as prompts for a conversation, not a scorecard."


How the pieces fit

Piece What it does Where you set it
Scanner for .NET Hooks MSBuild, runs Sonar's Roslyn rules, uploads results Pipeline step
Quality profile Which rules are active for C# Server, per language
Quality gate Pass/fail conditions on the analysis Server, per project
New code definition Which lines count as 'new' Project settings
Coverage import Reads coverlet / dotnet-coverage reports Scanner parameters
PR decoration Posts the gate result and issues on the PR DevOps platform integration

Editions (check the vendor's pricing page; as of November 2026)

Product Branch / PR analysis Notes
SonarQube Community Build No: main branch only Free, self-hosted
SonarQube Server Developer Edition Yes, with PR decoration Paid, priced by lines of code
Enterprise / Data Center Yes Portfolios, reports, high availability
SonarQube Cloud Yes SaaS; free for public projects, paid plans for private code

Gaming and how to counter it

Gaming pattern Counter
Tests that execute code without asserting Review tests in PRs, mutation testing (Stryker.NET) on core modules
Bulk Won't fix / False positive Restrict who can resolve, review resolutions weekly
Wide sonar.exclusions Exclusions changed only by PR with a reason
Splitting PRs to dodge conditions Gate on overall new code, not per-PR thresholds alone

Production example

On an invoicing platform of roughly [400k] lines, we started with the gate on new code only. Over six months the old issue count fell from [6,200] to [4,100] purely because touched files were cleaned, with no 'clean-up sprint', and the PR gate failed on about 1 in 12 PRs, almost always for missing tests on new branches of logic.

🔍 What the interviewer is checking

Checks whether the candidate can use SonarQube as a delivery tool (gates on new code, PR checks) rather than as a vanity dashboard.

Green flags

  • Explains begin / build / test / end and that coverage is imported
  • Understands the new code period and why it matters for legacy code
  • Knows Community Build lacks PR analysis
  • Names concrete gaming patterns and counters

Red flags

  • Wants 90% overall coverage enforced immediately
  • Thinks SonarQube runs tests or replaces code review
  • Can't explain what a quality gate is

📚 Learn in depth

1. What the scanner actually does

dotnet sonarscanner begin /k:"billing-api" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml"
        │  writes MSBuild targets that inject Sonar's analysers and settings
        ▼
dotnet build  ──► Roslyn runs SonarAnalyzer.CSharp + your analysers ──► results to .sonarqube/
        ▼
dotnet test --collect:"XPlat Code Coverage" ──► coverage files
        ▼
dotnet sonarscanner end ──► uploads results + coverage ──► server computes metrics and the gate

Because it hooks the build, the scanner cannot analyse C# without building it. A dotnet build --no-restore that is skipped or cached breaks the analysis, which is a common pipeline fault.

2. Issues, hotspots and metrics

  • Issues are rule violations, grouped by software quality (security, reliability, maintainability) and severity.
  • Security hotspots are code that may be risky (e.g. a regex on user input, a permissive CORS policy). A person must review each and mark it safe or fix it; they are not automatically vulnerabilities.
  • Metrics include coverage, duplication and technical debt estimates in minutes, derived from the rules' remediation cost.

3. New code and Clean as You Code

The new code period decides which lines are measured by the gate:

Definition Good for
Previous version Teams that release with version numbers
Number of days (e.g. 30) Continuous delivery without versions
Reference branch (main) Feature branches and PRs
Specific analysis A one-off baseline after a big change

Lines are attributed using SCM blame, so the scanner needs full git history (fetch-depth: 0 in GitHub Actions) or new code is computed wrongly.

4. Coverage import

Sonar does not run tests. You produce coverage with coverlet (--collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover) or dotnet-coverage collect -f xml, then pass sonar.cs.opencover.reportsPaths or sonar.cs.vscoveragexml.reportsPaths. Missing coverage shows as 0%, not as an error, so always check the report path.

5. Goodhart's law

When a measure becomes a target it stops being a good measure. Coverage measures executed lines, not verified behaviour; the duplication metric can be lowered by bad abstractions. Keep the gate small and pair it with human review.

Try it yourself

  1. Run SonarQube Community Build in Docker (docker run -p 9000:9000 sonarqube:community), analyse a sample API and look at the issues view.
  2. Add coverlet, generate OpenCover output and import it; deliberately break the path and see coverage drop to 0%.
  3. Create a custom quality gate with only three conditions and fail it with a new untested method.
  4. Set the new code definition to 'reference branch' and compare results for a feature branch.
  5. Write a test with no assert that raises coverage, then run Stryker.NET on the same class and compare the mutation score.

💻 Code

A GitHub Actions job that builds, tests with coverage and runs the SonarQube Cloud scanner; the gate result becomes a required PR check.

# .github/workflows/sonar.yml
name: sonar
on:
  pull_request:
  push:
    branches: [main]
jobs:
  analyse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0              # full history: needed for new-code and blame
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'
      - run: dotnet tool install --global dotnet-sonarscanner
      - name: Build, test and analyse
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          dotnet sonarscanner begin /k:"acme_billing-api" /o:"acme" \
            /d:sonar.host.url="https://sonarcloud.io" \
            /d:sonar.token="$SONAR_TOKEN" \
            /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" \
            /d:sonar.qualitygate.wait=true
          dotnet build Billing.slnx -c Release
          dotnet test Billing.slnx -c Release --no-build \
            --collect:"XPlat Code Coverage" \
            -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover
          dotnet sonarscanner end /d:sonar.token="$SONAR_TOKEN"

A test that games coverage versus one that earns it:

namespace Billing.Tests;

public class GstCalculatorTests
{
    [Fact] // Before: raises coverage, verifies nothing
    public void Calculate_runs() => new GstCalculator().Calculate(100m);

    [Theory] // After: the same lines covered, behaviour checked
    [InlineData(100.00, 10.00)]
    [InlineData(0.05, 0.01)]   // rounding: AwayFromZero to the cent
    public void Calculate_returns_ten_percent_rounded(decimal net, decimal expected) =>
        Assert.Equal(expected, new GstCalculator().Calculate(net));
}

public sealed class GstCalculator
{
    public decimal Calculate(decimal net) =>
        Math.Round(net * 0.10m, 2, MidpointRounding.AwayFromZero);
}

⚠ Common mistakes

  • Mistake: Gating on overall coverage for a legacy codebase. Why it is wrong: the gate fails forever and gets disabled. Instead: gate on new code and let old code improve as it is touched.
  • Mistake: Shallow git clone in CI. Why it is wrong: blame data is missing, so new code and issue assignment are wrong. Instead: fetch-depth: 0.
  • Mistake: Assuming the free Community Build (formerly Community Edition) can decorate pull requests. Why it is wrong: it analyses only the main branch. Instead: use Developer Edition or SonarQube Cloud, or accept post-merge feedback.
  • Mistake: Not importing coverage and wondering why it shows 0%. Why it is wrong: Sonar doesn't run tests. Instead: generate OpenCover/VS XML and set the report path.
  • Mistake: Treating security hotspots as confirmed vulnerabilities or ignoring them. Why it is wrong: they need a human decision. Instead: review each, mark safe with a comment or fix.
  • Mistake: Letting anyone bulk-resolve issues as Accepted (the status that replaced Won't fix in SonarQube 10.x) or False positive. Why it is wrong: the backlog vanishes without being fixed. Instead: restrict the 'Administer issues' permission to tech leads and review resolutions in the PR or weekly.
  • Mistake: Running the scanner as a separate, optional job nobody watches. Why it is wrong: results arrive after merge and are ignored. Instead: run it in the PR pipeline with sonar.qualitygate.wait=true and make the check required.
  • Mistake: Using the technical debt minutes as a planning estimate. Why it is wrong: they are per-rule constants, not real effort. Instead: use them for trend only.

🏛 Senior insight: trade-offs

The gate is a team agreement, not a tool setting. I'd agree three or four conditions with the team, make them a required PR check, and change them only through a retro. Everything else on the dashboard is information. The new-code approach is the only one I've seen work on large legacy systems, because it aligns the cost of improvement with work that is already happening.

Option When it fits Cost When not to
SDK analysers + .editorconfig only Small team, simple pipeline Free When you need history or PR-level gates across many repos
SonarQube Community Build Want dashboards, main-branch history Self-hosting, no PR gate When the PR gate is the main goal
SonarQube Server Developer+ Self-hosted, data must stay in your network (e.g. Azure Australia East VM) Licence by LOC + ops Few repos, no hosting skills
SonarQube Cloud GitHub / Azure DevOps teams, quick start Subscription; code analysed in vendor cloud Data residency rules forbid it

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions failing the build on warnings Why: Checks how they combine build-level enforcement with the Sonar gate
    How to answer

    The file under review turns on TreatWarningsAsErrors and then hides 25 warnings with NoWarn. That list includes nullable warnings, obsolete-API warnings and a security rule, so the policy looks strict while silencing the warnings that matter most. I'd remove those suppressions. Rules that genuinely don't apply would get a severity in .editorconfig, scoped to the right folders and commented. Rules we can't fix yet would go in WarningsNotAsErrors, so they stay visible as warnings. I'd also pin AnalysisLevel so an SDK upgrade can't break the build overnight, apply the same settings locally and in CI, and ratchet a legacy codebase towards zero warnings rather than flipping everything at once.

  2. When: Candidate mentions the coverage condition Why: Checks they tune exclusions deliberately rather than lowering the bar
    How to answer

    Separate generated or declarative files from code with behaviour. EF Core migrations, *.Designer.cs and model snapshots are generated: exclude them from coverage only with sonar.coverage.exclusions (e.g. **/Migrations/**), keep them in analysis, and record why in the repo. Plain DTOs (records with properties) usually have no logic worth testing; if they're failing the gate, check whether they actually contain validation, mapping or computed properties. If they do, that logic needs tests (validator tests, mapping tests), and it may belong in a validator or mapper rather than the DTO. Don't lower the threshold for everything; change exclusions only through a reviewed PR.

  3. When: Candidate mentions unused code or dead-code issues in Sonar Why: Checks they can act on findings safely
    How to answer

    Dead code isn't free: it slows reading, builds and reviews, widens the attack surface and misleads searches. Finding it takes layers of evidence:

    • Analysers prove private code is unused: IDE0051 (unused private member), IDE0052 (unread private member), IDE0060 (unused parameter). Rider's solution-wide analysis or NDepend extend this to public members inside the solution.
    • Telemetry proves what production runs: endpoint request counts in Application Insights, or a tombstone log you add to suspect code and watch for a full business cycle.
    • Coverage only shows what tests run, so it finds candidates, not proof.
    • Feature flags at 100% for weeks are dead branches waiting to be deleted.

    Then delete in small PRs; git is the backup. The trade-off: proving something unused takes time, so match the evidence to the risk.

🛠 Real-world problems: how you handle them

Quality gate disabled after a coverage target went wrong
Situation
An invoicing API of about [300k] lines, [3] teams. Management set the SonarQube gate to 85% overall coverage; the gate failed for every PR, so a team lead switched it to 'not required'. Within [two months] two regressions in GST rounding reached production.
Signals
Every PR showing a red gate that nobody looked at; coverage climbing while defects rose; tests with no assertions in reviews; dozens of issues resolved as Won't fix by one account.
Investigation
Pulled the gate history and issue resolution log from SonarQube; listed tests without asserts with a quick Roslyn query; ran Stryker.NET on the pricing module (mutation score [38%] despite [82%] coverage); compared defect tickets with modules.
Resolution
Immediately: replaced the gate with Sonar way on new code (reference branch main) and made it required again. Then: removed assert-free tests, added real tests for pricing, restricted Won't fix to tech leads with a weekly review.
Prevention
Gate conditions documented in an ADR; Stryker.NET nightly on core modules; PR template asks 'which behaviour do these tests verify?'; dashboard reviewed in retro, not in performance reviews.

How to tell it (STAR)

**S:** At [company] our SonarQube gate demanded 85% overall coverage on a [300k]-line billing API, so it failed on every PR and had been made optional. **T:** I was asked to get quality gating working again without stopping delivery. **A:** I showed the team that coverage had risen while mutation score on pricing was [38%], switched the gate to new-code conditions, made it required, and restricted bulk resolutions. **R:** The gate passed on [92%] of PRs first time within a month, and we had [zero] pricing regressions in the next [two] quarters.

↩ Usually asked after

More in Static Analysis

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me