Testing Setup and Runners
Level: Intermediate
ℹ️ What You'll Learn
- Create test projects
- Configure xUnit/NUnit
- Run tests in Visual Studio
- Test Explorer window
- Coverage analysis
Create Test Project
File → New Project → xUnit Test Project:
Project name: SMS.Tests
Location: C:\NexCoding\SMS\
Framework: .NET 8
Structure:
SMS.Tests/
├── SMS.Tests.csproj
├── UnitTest1.cs
├── Usings.cs
└── bin/obj/
Add Project Reference
Right-click SMS.Tests → Add Reference → SMS.Core
Now can test SMS.Core code.
Write First Test
File: StudentServiceTests.cs
using Xunit;
using SMS.Services;
public class StudentServiceTests
{
[Fact]
public void GetStudent_WithValidId_ReturnsStudent()
{
// Arrange
var service = new StudentService();
int studentId = 101;
// Act
var result = service.GetStudent(studentId);
// Assert
Assert.NotNull(result);
Assert.Equal("Ravi Kumar", result.Name);
Assert.Equal("10-A", result.ClassName);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void GetStudent_WithInvalidId_ThrowsException(int id)
{
var service = new StudentService();
Assert.Throws<ArgumentException>(() => service.GetStudent(id));
}
}
Test Explorer
View → Test Explorer (or Ctrl + E, T):
SMS.Tests
├── ✓ GetStudent_WithValidId_ReturnsStudent (passed)
├── ✓ GetStudent_WithInvalidId_ThrowsException[0] (passed)
└── ✓ GetStudent_WithInvalidId_ThrowsException[-1] (passed)
Run tests:
- Run All: Ctrl + R, A
- Run Failed: Ctrl + R, F
- Run Selected: Select test → Ctrl + R, T
NUnit vs xUnit
xUnit (recommended):
[Fact] // One test
[Theory] // Multiple test cases
[InlineData(...)] // Inline test data
NUnit:
[Test] // One test
[TestCase(...)] // Multiple test cases
[Values(...)] // Value parameters
Both work. Choose one per project.
Test Coverage
Analyze → Code Coverage → Measure Code Coverage:
StudentService.cs:
- GetStudent(): ✓ 100% covered
- GetStudents(): ✗ 60% covered (missing edge cases)
- DeleteStudent(): ✗ 0% covered (no tests)
Aim for 80%+ coverage.
Key Takeaways
- Create separate test project
- Test = Arrange, Act, Assert
- xUnit = cleaner syntax
- Test Explorer = run/debug tests
- Coverage = measure test completeness
💡 Testing Pro Tip
Write tests first (TDD), then implementation. Tests document expected behavior.
🤖Use AI to Learn Faster
Use ChatGPT, Claude, or Copilot to go deeper on Visual Studio Testing. Try these prompts:
"How do I create a test project?""What's the difference between Fact and Theory?""Quiz me on testing"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
nexcoding.in
Have questions on your tech stack, ongoing projects, or need one-to-one training?