Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
Unit Testing C# Programming Tutorial · Testing
Unit testing involves testing the smallest parts of an application (units) independently to
ensure they work correctly. It is important because it helps detect bugs early, improves code
quality, supports refactoring, and provides documentation for expected behavior.
Unit Testing C# Programming Tutorial · Testing
Review the concept and prepare a concise verbal explanation with a real project example.
Unit Testing C# Programming Tutorial · Testing
A good unit test is:
Unit Testing C# Programming Tutorial · Testing
Review the concept and prepare a concise verbal explanation with a real project example.
Unit Testing C# Programming Tutorial · Testing
Review the concept and prepare a concise verbal explanation with a real project example.
Unit Testing C# Programming Tutorial · Testing
Focus on testing:
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Challenges include:
Unit Testing C# Programming Tutorial · Testing
Use mocking or stubbing frameworks (e.g., Moq, NSubstitute) to replace real
dependencies with controlled test doubles, allowing tests to focus on the unit under test.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Assertions verify that the actual outcome of a test matches the expected result, determining
if a test passes or fails.
Unit Testing C# Programming Tutorial · Testing
Code coverage measures the percentage of code executed by tests. It helps identify
untested parts but doesn’t guarantee test quality. High coverage with meaningful tests
improves confidence in code correctness.
xUnit Framework
Unit Testing C# Programming Tutorial · Testing
xUnit is a free, open-source unit testing framework for .NET, designed by the original
authors of NUnit. It’s popular because it supports modern testing practices, is lightweight,
extensible, integrates well with .NET Core and Visual Studio, and encourages clean,
maintainable test code.
Unit Testing C# Programming Tutorial · Testing
[Test] and [TestMethod].
and constructor/dispose patterns.
default.
Unit Testing C# Programming Tutorial · Testing
public class CalculatorTests
[Fact]
public void Add_ReturnsSum()
var calculator = new Calculator();
var result = calculator.Add(2, 3);
Assert.Equal(5, result);
Unit Testing C# Programming Tutorial · Testing
inputs, provided by [InlineData] or other data sources.
Unit Testing C# Programming Tutorial · Testing
Using [Theory] and data attributes like [InlineData]:
[Theory]
[InlineData(2, 3, 5)]
[InlineData(10, 20, 30)]
public void Add_ReturnsSum(int a, int b, int expected)
var calculator = new Calculator();
var result = calculator.Add(a, b);
Assert.Equal(expected, result);
Unit Testing C# Programming Tutorial · Testing
Example:
public class DatabaseTests : IDisposable
public DatabaseTests()
// Setup
[Fact]
public void TestMethod() { }
public void Dispose()
// Cleanup
For shared context across multiple tests, use class fixtures or collection fixtures.
Unit Testing C# Programming Tutorial · Testing
Use the Skip property on [Fact] or [Theory]:
[Fact(Skip = "Reason for skipping")]
public void SkippedTest() { }
Unit Testing C# Programming Tutorial · Testing
run in parallel.
[Collection("Database collection")]
public class TestClass1 { }
[Collection("Database collection")]
public class TestClass2 { }
Unit Testing C# Programming Tutorial · Testing
Test fixtures provide a way to share setup and cleanup code between tests. xUnit supports:
They are implemented by creating a fixture class and injecting it into test classes via
constructor.
Unit Testing C# Programming Tutorial · Testing
Use the dotnet test CLI command:
dotnet test YourTestProject.csproj
This runs all tests in the project and outputs results in the console. Additional options allow
filtering and outputting reports.
NUnit Framework
Unit Testing C# Programming Tutorial · Testing
NUnit is a popular open-source unit testing framework for .NET. It allows developers to write
and run automated tests by marking test methods with attributes. NUnit discovers and
executes these tests, verifying that the code behaves as expected.
Unit Testing C# Programming Tutorial · Testing
constructors and IDisposable.
[InlineData].
Unit Testing C# Programming Tutorial · Testing
[TestCase(2, 3, 5)]
[TestCase(10, 20, 30)]
public void Add_ReturnsSum(int a, int b, int expected)
var calculator = new Calculator();
var result = calculator.Add(a, b);
Assert.AreEqual(expected, result);
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
[Test]
public void Divide_ByZero_ThrowsException()
var calculator = new Calculator();
Assert.Throws<DivideByZeroException>(() => calculator.Divide(10,
0));
Unit Testing C# Programming Tutorial · Testing
Use the [Category("CategoryName")] attribute to group tests, allowing filtering by
category during test runs.
[Test, Category("Integration")]
public void IntegrationTest() { }
Unit Testing C# Programming Tutorial · Testing
different inputs.
Unit Testing C# Programming Tutorial · Testing
Use [Ignore("Reason")] to skip tests unconditionally, or [Category] combined with
test runner filters. For conditional ignoring, you can use Assume statements or custom logic
inside tests.
Unit Testing C# Programming Tutorial · Testing
Download and use nunit3-console.exe from NUnit site:
nunit3-console.exe YourTestAssembly.dll
It runs all tests in the assembly and outputs results.
Unit Testing C# Programming Tutorial · Testing
Yes, NUnit integrates seamlessly with CI/CD tools like Azure DevOps, Jenkins, GitHub
Actions, and others using command-line runners or plugins, allowing automated test
execution during builds and deployments.
MSTest Framework
Unit Testing C# Programming Tutorial · Testing
MSTest is Microsoft's official unit testing framework for .NET. It’s tightly integrated with
Visual Studio and is a good choice for teams using Microsoft tooling and wanting a
straightforward, supported testing solution without external dependencies.
Unit Testing C# Programming Tutorial · Testing
[TestClass]
public class CalculatorTests
[TestMethod]
public void Add_ReturnsSum()
var calculator = new Calculator();
var result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
Unit Testing C# Programming Tutorial · Testing
NUnit uses [Test].
xUnit’s [Theory].
Unit Testing C# Programming Tutorial · Testing
[TestInitialize]
public void Setup() { /* setup code */ }
[TestCleanup]
public void Cleanup() { /* cleanup code */ }
Unit Testing C# Programming Tutorial · Testing
[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public void Divide_ByZero_ThrowsException()
var calculator = new Calculator();
calculator.Divide(10, 0);
Unit Testing C# Programming Tutorial · Testing
Yes, MSTest supports data-driven tests using [DataTestMethod] and [DataRow]
attributes:
[DataTestMethod]
[DataRow(2, 3, 5)]
[DataRow(10, 20, 30)]
public void Add_ReturnsSum(int a, int b, int expected)
var calculator = new Calculator();
var result = calculator.Add(a, b);
Assert.AreEqual(expected, result);
Unit Testing C# Programming Tutorial · Testing
Use the [TestCategory("CategoryName")] attribute to group tests for filtering.
[TestMethod]
[TestCategory("Integration")]
public void IntegrationTest() { }
Unit Testing C# Programming Tutorial · Testing
Use the [Ignore("Reason")] attribute on the test method or class.
[Ignore("Test is temporarily disabled")]
[TestMethod]
public void SkippedTest() { }
Unit Testing C# Programming Tutorial · Testing
Use dotnet test CLI for .NET Core MSTest projects:
dotnet test YourTestProject.csproj
In Azure DevOps, use the Visual Studio Test task or the DotNetCoreCLI task to run tests
during builds and releases.
Unit Testing C# Programming Tutorial · Testing
MSTest itself does not provide mocking capabilities. Use mocking libraries like Moq or
NSubstitute alongside MSTest to mock dependencies.
Example with Moq:
var mockService = new Mock<IService>();
mockService.Setup(s => s.GetData()).Returns("Test Data");
Moq Framework (Mocking)
Unit Testing C# Programming Tutorial · Testing
Mocking is creating fake objects that simulate the behavior of real dependencies. It’s
important because it isolates the unit under test, avoids reliance on external systems,
improves test speed, and allows testing specific scenarios and edge cases.
Unit Testing C# Programming Tutorial · Testing
Moq is a popular, open-source mocking library for .NET that enables developers to create
mock objects, set expectations, and verify interactions in unit tests, helping isolate
dependencies easily.
Unit Testing C# Programming Tutorial · Testing
var mockService = new Mock<IService>();
var service = mockService.Object; // use this in your test
Unit Testing C# Programming Tutorial · Testing
mockService.Setup(s => s.GetData()).Returns("Mocked Data");
This configures the mock to return "Mocked Data" when GetData() is called.
Unit Testing C# Programming Tutorial · Testing
mockService.Verify(s => s.Save(), Times.Once);
This asserts that Save() was called exactly once during the test.
Unit Testing C# Programming Tutorial · Testing
mockService.SetupGet(s => s.Name).Returns("MockName");
This sets up a mocked property getter to return a specific value.
Unit Testing C# Programming Tutorial · Testing
mockService.Setup(s => s.GetData(It.IsAny<int>())).Returns("Data");
You can specify argument matchers like It.IsAny<T>() to mock methods with
parameters.
Unit Testing C# Programming Tutorial · Testing
mockService.Setup(s => s.GetDataAsync()).ReturnsAsync("Async Data");
Moq supports ReturnsAsync to mock async methods returning Task<T>.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
classes or non-virtual methods.
easier mocking.
Test Driven Development (TDD)
Unit Testing C# Programming Tutorial · Testing
TDD is a software development approach where you write tests before writing the actual
code. It follows a short, repetitive cycle of writing a failing test, implementing code to pass
the test, and then refactoring.
Unit Testing C# Programming Tutorial · Testing
Review the concept and prepare a concise verbal explanation with a real project example.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
TDD relies heavily on unit tests as the foundation. It’s a process where unit tests are
created first to define requirements, then production code is written to pass those tests.
Unit Testing C# Programming Tutorial · Testing
(Example) I wrote a simple calculator class using TDD: First, I wrote a test for addition, saw
it fail, implemented Add() method, passed the test, then refactored. Repeated for
subtraction, multiplication, etc., ensuring robust code with full test coverage.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Use mocking and dependency injection to isolate the unit under test, allowing tests to
focus on behavior without relying on external resources.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
more manual or batch-driven.
Integration Testing
Unit Testing C# Programming Tutorial · Testing
Integration testing verifies that multiple components or systems work together correctly,
unlike unit testing which tests individual units in isolation. It focuses on interactions between
modules, databases, APIs, or external services.
Unit Testing C# Programming Tutorial · Testing
You write integration tests by creating test projects that exercise multiple components
together, often involving real or in-memory databases, services, or APIs. You use
frameworks like xUnit or NUnit and configure dependencies to mimic production-like
environments.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
You use a test database or in-memory database to run queries and verify data persistence
and retrieval, ensuring the data layer works as expected without affecting production data.
Unit Testing C# Programming Tutorial · Testing
Use separate configuration files or environment variables for tests, injecting connection
strings and service endpoints specific to the test environment.
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Mocking/stubbing replaces external dependencies like web services or message queues
with controlled test doubles to isolate the parts under test and control external behavior
without invoking real services.
Unit Testing C# Programming Tutorial · Testing
Configure pipeline steps to run integration tests after build, using test runners, setting up
test databases, and cleaning up after tests. Use containers or managed services to mimic
production-like environments.
Unit Testing C# Programming Tutorial · Testing
Leverage dependency injection to replace real services with test implementations or mocks.
Use setup and teardown methods to initialize and dispose of dependencies per test.
Unit Testing C# Programming Tutorial · Testing
In-memory databases allow fast, isolated testing of data access code without a real
database, making integration tests easier to run and maintain, but may lack certain
behaviors of real databases (like relational constraints).
Practical & Advanced Topics
Unit Testing C# Programming Tutorial · Testing
Typically, test projects mirror the structure of the production projects, organized by feature
or layer. For example, you might have MyApp.Core.Tests, MyApp.Web.Tests, and
MyApp.Data.Tests. Tests are grouped by functionality to keep code maintainable and
discoverable.
Unit Testing C# Programming Tutorial · Testing
Use mocking frameworks like Moq to create mock implementations of service interfaces.
For HTTP calls, tools like HttpClientFactory with a mocked HttpMessageHandler or
libraries like RichardSzalay.MockHttp help simulate HTTP responses.
Unit Testing C# Programming Tutorial · Testing
Dependency Injection (DI) is a design pattern where dependencies are provided rather than
created inside a class. DI makes testing easier by allowing tests to inject mock or fake
implementations of dependencies, isolating the unit under test.
Unit Testing C# Programming Tutorial · Testing
Best practice is to test private methods indirectly through public methods. If needed, internal
methods can be exposed to test projects using InternalsVisibleTo attribute. Reflection
can be used but is generally discouraged as it breaks encapsulation.
Unit Testing C# Programming Tutorial · Testing
Mark test methods with async Task and use await to call asynchronous methods. Most
test frameworks like xUnit, NUnit, and MSTest support async tests natively.
[TestMethod]
public async Task AsyncMethod_ShouldReturnTrue()
var result = await myService.DoWorkAsync();
Assert.IsTrue(result);
Unit Testing C# Programming Tutorial · Testing
Use assertion methods that expect exceptions. For example, in MSTest:
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void Method_ShouldThrowException()
myService.DoSomethingInvalid();
Or in xUnit:
await Assert.ThrowsAsync<InvalidOperationException>(() =>
myService.DoSomethingInvalidAsync());
Unit Testing C# Programming Tutorial · Testing
Test doubles are objects used in place of real components for testing. Types include:
Unit Testing C# Programming Tutorial · Testing
Unit Testing C# Programming Tutorial · Testing
Use built-in test runner features in frameworks like xUnit or NUnit to enable parallelization.
Configure CollectionBehavior or run tests in separate processes/threads, ensuring
tests are independent and stateless.
Unit Testing C# Programming Tutorial · Testing
Scenario-Based / Behavioral
Questions
Unit Testing C# Programming Tutorial · Testing
In one project, a unit test caught a null reference exception caused by missing initialization.
This early detection prevented the bug from reaching production, saving hours of debugging
and user impact.
Unit Testing C# Programming Tutorial · Testing
I highlight the long-term benefits like reduced bugs, easier refactoring, and faster
debugging. Demonstrating quick wins with simple tests and integrating tests gradually helps
ease resistance.
Unit Testing C# Programming Tutorial · Testing
I prioritize critical features for testing, use automated tests to speed up validation, and
integrate testing into the development process rather than as a separate phase to maintain
quality without delaying delivery.
Unit Testing C# Programming Tutorial · Testing
I once refactored a tightly coupled class by introducing interfaces and dependency injection,
enabling mock dependencies and isolated unit testing, which improved code quality and test
coverage.
Unit Testing C# Programming Tutorial · Testing
Start by identifying seams to isolate dependencies, use characterization tests to capture
existing behavior, refactor incrementally, and introduce tests gradually without breaking
functionality.
Unit Testing C# Programming Tutorial · Testing
A concurrency issue that only appeared under load was caught by a combination of unit and
integration tests with parallel execution. It was tricky to reproduce but testing helped identify
race conditions.
Unit Testing C# Programming Tutorial · Testing
Use setup/teardown hooks, leverage containerization (Docker) for dependencies, and mock
external services where possible to simplify environment setup and ensure tests are
reproducible.
Unit Testing C# Programming Tutorial · Testing
Write clear, focused tests with descriptive names, avoid duplication with setup helpers, keep
tests independent, and regularly refactor tests alongside production code.
Unit Testing C# Programming Tutorial · Testing
I have implemented CI/CD pipelines integrating xUnit tests, automated database resets, and
used mocking extensively to achieve reliable, fast test runs that provide immediate feedback.
Unit Testing C# Programming Tutorial · Testing
I organize hands-on workshops, code reviews focusing on test quality, pair programming
sessions, and provide resources emphasizing the value of tests and how to write effective,
maintainable tests.
Miscellaneous
Unit Testing C# Programming Tutorial · Testing
The Assert class provides methods to verify conditions in tests, such as equality, truth,
exceptions, or null values. It determines whether a test passes or fails based on these
validations.
Unit Testing C# Programming Tutorial · Testing
Identify and fix root causes like race conditions or dependencies on external systems. Use
mocking, isolate tests, avoid shared state, and if necessary, temporarily quarantine flaky
tests while prioritizing fixes.
Unit Testing C# Programming Tutorial · Testing
interactions.
what happened rather than controlling behavior.
Unit Testing C# Programming Tutorial · Testing
Subscribe to events in the test, trigger the event source, then verify that event handlers
execute expected logic or side effects using assertions or mocks.
Unit Testing C# Programming Tutorial · Testing
Refactor static methods into instance methods where possible for easier testing.
Alternatively, wrap static calls in interfaces or use tools like Microsoft Fakes or JustMock that
support static mocking.
Unit Testing C# Programming Tutorial · Testing
Typically, I aim for at least 80% coverage on critical code paths, but focus more on
meaningful coverage rather than just numbers. Coverage alone doesn’t guarantee quality.
Unit Testing C# Programming Tutorial · Testing
Test private members indirectly through public methods. For internal members, use the
[InternalsVisibleTo] attribute to expose them to test assemblies.
Unit Testing C# Programming Tutorial · Testing
Automated tests run on every code change, catching regressions early, ensuring consistent
quality, enabling faster feedback, and supporting safer, more frequent releases.
Unit Testing C# Programming Tutorial · Testing
Popular tools include Coverlet, Visual Studio Code Coverage, dotCover by JetBrains,
and OpenCover, often integrated with CI pipelines.
Unit Testing C# Programming Tutorial · Testing
Use clear, descriptive names; keep tests small and focused; avoid logic inside tests; use
setup/teardown methods for common code; and ensure tests are independent and
deterministic.
Unit Testing C# Programming Tutorial · Testing
Maintain backward-compatible tests for shared components, use feature flags to isolate new
behaviors, update tests alongside code changes, and maintain multiple test branches if
necessary.