C# Unit Testing Interview Questions: xUnit, NUnit and MSTest

Reviewed by Mark Dickie · Last updated

5 questions on this page you can answer and see marked on the spot. Go to the first one

C# unit testing is the practice of checking one class or method in isolation, using a framework such as xUnit, NUnit or MSTest to run and report the result. Interviewers mostly test whether you can explain the attributes and lifecycle of each framework, and whether you can isolate a unit by replacing databases, clocks and HTTP clients with test doubles. Be ready to say why an async test that returns void can pass even when its assertions fail.

What do C# unit testing interviews check?

TopicWhat to be ready to explain
xUnit [Fact] and [Theory][Theory] with [InlineData] runs one method against many inputs, and xUnit builds a new test class instance for every test, so there is no [SetUp]
NUnit [Test] and [TestCase][SetUp] and [TearDown] run around each test, while [OneTimeSetUp] runs once per fixture
MSTest [TestMethod] and [DataRow][TestInitialize] runs before each test and [ClassInitialize] runs once per class
Mocking with Moq or NSubstituteMock<T>.Setup stubs return values and Verify checks that a call happened; a hand-written fake suits cases where the behaviour matters more than the call count
async Task testsAn async void test is not awaited by the runner, so an exception after the first await can go unreported and the test passes

How do you practise C# unit testing before the interview?

  1. Write a [Theory] for a PriceCalculator method, with InlineData rows for zero, negative and boundary quantities.
  2. Replace a direct DateTime.UtcNow call with an IClock interface, then write a fake that returns a fixed date so the test gives the same result on any day.
  3. Mock a repository interface with Moq, call SaveAsync from the code under test, and Verify it ran exactly once.
  4. Change one async void test to async Task, then introduce a deliberate bug and confirm the test now fails.

Key facts

  • Tarmac has 13 C# interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 871 job postings asking for C# in November 2026.
  • Roles asking for C# advertise a median base salary of £70,000, across 342 job postings as of November 2026.
  • Tarmac last reviewed these C# interview questions on 23 November 2026.

At a glance

Questions10 shown · 13 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Multiple answer, Fill in the blank, True / false, Find the bug, Short answer, Flashcard, Code output, Ordering

What you'll review

  1. unit testing csharp

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

In xUnit.net (v2), which attribute marks a method as a single test that takes no parameters?#

Options

Show answer

In xUnit.net, the [Fact] attribute marks a parameterless test method. [Theory] is for parameterized tests that get their data from attributes like [InlineData]. [TestMethod] belongs to MSTest and [Test] belongs to NUnit.

Why:

In xUnit.net, [Fact] marks a parameterless test method. [Theory] is also xUnit, but it's for data-driven tests that take parameters supplied by attributes like [InlineData]. [TestMethod] comes from MSTest and [Test] comes from NUnit, so xUnit doesn't recognize either one.

In NUnit 3, which of the following attributes are valid ways to mark a method as a test or as test setup/teardown? Select all that apply.#

Options

Pick every one that applies.

Show answer

NUnit 3 marks a test method with [Test], a method that runs before each test with [SetUp], and a method that runs after each test with [TearDown]. The [Fact] attribute belongs to xUnit.net and [TestMethod] belongs to MSTest, so NUnit's runner ignores both.

Why:

NUnit 3 uses [Test] to mark a test method, [SetUp] for a method that runs before each test, and [TearDown] for a method that runs after each test. [Fact] comes from xUnit.net and [TestMethod] comes from MSTest. NUnit does not recognize either of them, so methods marked with them are not discovered as NUnit tests.

In MSTest (v2/v3), the class that holds the tests is marked with the [_____] attribute, and each test method inside it is marked with the [_____] attribute.#

Show answer

In MSTest (v2/v3), the class that holds the tests is marked with the [**TestClass**] attribute, and each test method inside it is marked with the [**TestMethod**] attribute.

Why:

MSTest finds tests through two attributes. [TestClass] goes on the class, and [TestMethod] goes on each method that should run as a test. If the class is missing [TestClass], the runner skips it entirely. The other frameworks use different names: xUnit uses [Fact] and needs no class attribute, and NUnit uses [TestFixture] (optional in NUnit 3) and [Test]. C# also lets you write the full attribute names with the Attribute suffix, so TestClassAttribute and TestMethodAttribute are accepted too.

In xUnit.net (v2), you want one test method to run multiple times with different inline input values. Which attribute combination is correct?#

Options

Show answer

In xUnit.net, you write a parameterized test by marking the method with [Theory] and adding one [InlineData(...)] attribute for each set of arguments. The method runs once for each data row. A [Fact] is for tests that take no parameters. [TestCase] and [Test] are NUnit attributes, and [TestMethod] is MSTest.

Why:

xUnit.net uses [Theory] for parameterized tests, and each [InlineData(...)] attribute supplies one set of arguments. A [Fact] takes no parameters and does not accept data rows. [TestMethod] belongs to MSTest and [TestCase] belongs to NUnit, so combining them is wrong. [Test] is NUnit's attribute, so pairing it with xUnit's [InlineData] is wrong too.

In xUnit.net (v2), a new instance of the test class is created for each test method that runs, so instance fields set in the constructor are not shared between tests in that class.#

Options

Show answer

xUnit.net creates a new test class instance for every test method it runs, including each [Theory] data row. So the constructor works as per-test setup and instance fields are never shared between tests. To share expensive state on purpose, use IClassFixture<T> or a collection fixture.

Why:

xUnit.net creates a new instance of the test class for every test it runs, including each data row of a [Theory]. That means the constructor works as per-test setup and Dispose (from IDisposable) works as per-test teardown. Instance fields start fresh for every test, which keeps tests isolated. To share expensive state across the tests in a class, you have to opt in with IClassFixture<T>. To share it across several classes, use a collection fixture.

This xUnit test is meant to verify that Withdraw throws when the balance is too low, but it passes even when Withdraw throws nothing. Which line contains the bug?#

[Fact]
public async Task Withdraw_Overdraft_Throws()
{
    var account = new Account(balance: 10m);
    Assert.ThrowsAsync<InvalidOperationException>(
        () => account.WithdrawAsync(50m));
}
Show answer

The bug is on line 5.

Why:

Assert.ThrowsAsync returns a Task that holds the result of the assertion. Line 5 never awaits that task, so the test method finishes and passes before anything is checked. Any failure is lost in a task nobody observes. The fix is await Assert.ThrowsAsync<InvalidOperationException>(...). Recent xUnit analyzers flag this with warning xUnit2021. The other lines are fine: the method is async Task and the lambda returns the task from WithdrawAsync.

In xUnit.net (v2), a test class has an expensive setup step: it starts an in-memory database. Right now it runs in the class constructor and is cleaned up in Dispose. A teammate notices it runs once for every test method, not once for the class. Explain why xUnit does this, and name the mechanism you would use so that all tests in that one class share a single database instance.#

Show answer

xUnit creates a new instance of the test class for every test method. That keeps tests isolated, so the constructor and Dispose run once per test. To share setup across the tests in one class, write a fixture class that does the setup in its constructor and the cleanup in IDisposable.Dispose (or IAsyncLifetime). Then have the test class implement IClassFixture<DatabaseFixture> and accept the fixture as a constructor parameter. xUnit creates the fixture once, injects it into every test instance, and disposes it after the class's last test. To share it across several classes, use [CollectionDefinition] with ICollectionFixture<T> instead.

Why:

xUnit deliberately creates a fresh test-class instance for every test, so state isn't shared by accident. That means the constructor and Dispose act as per-test setup and teardown. For shared, expensive context, xUnit provides class fixtures. You implement IClassFixture<TFixture>, and the framework builds TFixture once, injects it through the constructor, and disposes it after all tests in the class have run. Collection fixtures (ICollectionFixture<T>) do the same job across several classes.

In xUnit.net v2, how many times is a test class's constructor (and Dispose) run, and how do you share an expensive setup object, such as a database container, across all tests in one class? What about sharing it across several classes?#

Show answer

xUnit makes a new instance of the test class for every test method, so the constructor and Dispose run once per test. To share setup within one class, implement IClassFixture<TFixture> and take TFixture as a constructor parameter. xUnit builds the fixture once before the class's first test and disposes it after the last. To share across classes, define a [CollectionDefinition("Name")] class that implements ICollectionFixture<TFixture>, then mark each test class with [Collection("Name")]. Classes in the same collection do not run in parallel with each other. For async setup or teardown, have the fixture implement IAsyncLifetime.

Why:

xUnit creates a fresh class instance per test on purpose, so tests stay isolated. That makes the constructor the place for per-test setup. Expensive shared state needs an explicit lifetime: a class fixture lives for one class, and a collection fixture lives for a named group of classes. A common senior-level mistake is putting heavy setup in the constructor, which runs once per test, or using static fields, which skips disposal and can break parallel runs.

Using Moq 4.x with the default MockBehavior.Loose, what does this program print?#

using System;
using Moq;

public interface IRepo { int Get(int id); }

public static class Program
{
    public static void Main()
    {
        var m = new Mock<IRepo>();
        m.Setup(r => r.Get(5)).Returns(2);
        m.Setup(r => r.Get(It.IsAny<int>())).Returns(1);
        m.Setup(r => r.Get(It.Is<int>(i => i > 10))).Returns(3);

        var o = m.Object;
        Console.WriteLine($"{o.Get(5)} {o.Get(20)} {o.Get(7)}");
    }
}
Show answer
1 3 1
Why:

In Moq, when more than one setup matches a call, the setup added most recently wins. Moq does not choose the most specific match. Get(5) matches the 5 setup and the It.IsAny<int>() setup but fails the i > 10 check. Of the two that match, IsAny was added later, so it hides the exact-value setup and the call returns 1. Get(20) matches both IsAny and i > 10. The i > 10 setup was added last, so the call returns 3. Get(7) matches only IsAny and returns 1. The program prints 1 3 1. Because of this behavior, catch-all setups should be added before the more specific ones.

In xUnit.net v2, test class OrderTests is the only class in collection "Db". The collection definition uses ICollectionFixture<DbFixture>. OrderTests implements IClassFixture<CacheFixture>, IAsyncLifetime and IDisposable, and has exactly one [Fact]. Both fixtures implement only IDisposable. Put these lifecycle events in the order in which xUnit runs them during that run.#

Put these in order

Show answer

In xUnit.net v2 the order is: collection fixture constructor, class fixture constructor, test class constructor, InitializeAsync, test body, DisposeAsync, test class Dispose, class fixture Dispose, collection fixture Dispose. Fixtures are created from the outside in, and they are torn down in reverse. On the test class instance, async disposal runs before synchronous disposal.

Why:

xUnit v2 sets up fixtures from the outside in. The collection runner creates collection fixtures before it runs any class in the collection, and the class runner then creates class fixtures. Those fixture instances are injected when the test class is constructed. Because the test class implements IAsyncLifetime, InitializeAsync runs after the constructor and before the test body. After the test, DisposeAsync runs first and then the synchronous IDisposable.Dispose on the test class instance. The class fixture is disposed when every test in the class has finished. The collection fixture is disposed last, after every class in the collection is done. Teardown is the mirror image of setup.

Related interview questions

Job market

See csharp salaries and hiring demand from live job postings.

The other 3 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 3 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.