Niloufar Mohammadi
Niloufar Mohammadi

Reputation: 23

Multiple Unit Tests' Running With multiple Connections To Database

In the Asp.Net core project, there are several unit tests used services for connecting to the database and bring real data, so multiple concurrent connections are created. When these tests run, I received this error

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

but I do not know how can I fix this error without using async ways.

Upvotes: 1

Views: 326

Answers (1)

Svenmarim
Svenmarim

Reputation: 3735

In unit tests you should not use connection to a DB. You should use mockups and create your own data to test with.

Use the NuGet package moqto easily create mockup objects.

Example of using the mockup objects:

public void Test_Login()
    {
        Mock<IDatabase> mockDatabase = new Mock<IDatabase>();
        mockDatabase.Setup(p => p.GetAccountAsync(It.IsAny<string>()))
            .Returns((string givenEmail) => Task.FromResult(new Account(1, "test", givenEmail, "123", "$2b$10$pfsnDQ3IWuY/zER/uBQpedvRFntMNHGOGhOSpABKZ7bwS", false)));

        Mock<IConfiguration> mockConfiguration = new Mock<IConfiguration>();
        Mock<IHostingEnvironment> mockHostingEnvironment = new Mock<IHostingEnvironment>();

        AccountService accountService = new AccountService(mockDatabase.Object, mockConfiguration.Object, mockHostingEnvironment.Object);

        LoginViewModel loginViewModel = new LoginViewModel
        {
            EmailLogin = "[email protected]",
            PasswordLogin = "s"
        };

        Task<Account> account = accountService.LoginAsync(loginViewModel);

        Assert.NotNull(account.Result);
        Assert.Equal(loginViewModel.EmailLogin, account.Result.Email);
    }

In the example above I manually set the value of the mockup database that the service method will use to retrieve the account and compare the returned email with the given email.

Upvotes: 1

Related Questions