Useful Unit Testing Tools with EFCore In-Memory, NSubsititue, and Shouldly

Ha Doan
2 min readApr 29, 2020

--

Recently I have to write unit tests in C# application and I found out that there are some useful tools that make unit tests easier

  • In our daily work, I have to verify logic in database, and I noticed that it would be take time to prepare data for inserting/query from real database (e.g Sql Server, MySql). In this case, I config to use InMemory database as below:

Add EFCore In-Memory Database provider

dotnet add package Microsoft.EntityFrameworkCore.InMemory

Then we can config to use In-Memory by using UseInMemoryDatabase extension method and write a test function with ease

  • When doing Mock/Fake services, compare to old library like Moq, I am switching to more friendly library called NSubsitue

For example, I have ICalculator interface

public interface ICalculator
{
int Add(int a, int b);
string Mode { get; set; }
event Action PoweringUp;
}

We can mock/stub/fake,… by more friendly way:

_calculator = Substitute.For<ICalculator>();

We can easy setup call like this:

_calculator.Add(1, 2).Returns(3);
Assert.That(_calculator.Add(1, 2), Is.EqualTo(3));
  • Are you bored with Assert syntax?
[Fact]
public void PassingTest()
{
Assert.Equal(4, Add(2, 2));
}

It is time to move to Shouldy

[Fact]
public void PassingTest()
{
Add(2, 2).ShouldBe(4);
}
Assert.That(map.IndexOfValue("boo"), Is.EqualTo(2)); // -> Expected 2 but was -1
map.IndexOfValue("boo").ShouldBe(2); // -> map.IndexOfValue("boo") should be 2 but was -1

Enjoy unit testing!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response