C# Unit Test : How can I mock Database GetDbConnection() CreateCommand?

109 Views Asked by At

I've set up a mock database that works well - allowing me to test IF Statements below BUT line 55 calls a method that ultimately uses SQL to retrieve data from a database. So when the test progresses through to line 77, the unit test falls over with the following ERROR message :

System.InvalidOperationException: Relational-specific methods can only be used when the context is using a relational database provider.
       at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetFacadeDependencies(DatabaseFacade databaseFacade)
       at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetDbConnection(DatabaseFacade databaseFacade)
       at Clarity.Processes.Application.v0_3.TeamActivities.Handlers.ListTeamActivitiesByTeamHandler.GetTeamTasksQueryCommand(String teamId, Nullable`1 clusterId, String searchTerm, Nullable`1 processDefinitionHeaderId, Boolean expired, Boolean paused, Nullable`1 pageSize, Nullable`1 pageNumber) in C:\Source\Compliance\Clarity.Processes.Api\src\Clarity.Processes.Application\v0_3\TeamActivities\Handlers\ListTeamActivitiesByTeamHandler.cs:line 77
       at Clarity.Processes.Application.v0_3.TeamActivities.Handlers.ListTeamActivitiesByTeamHandler.Handle(ListTeamActivitiesByTeamQuery query, CancellationToken cancellationToken) in C:\Source\Compliance\Clarity.Processes.Api\src\Clarity.Processes.Application\v0_3\TeamActivities\Handlers\ListTeamActivitiesByTeamHandler.cs:line 55
       at Clarity.Processes.Application.Unit.Tests.v0_3.TeamActivities.Handlers.ListTeamActivitiesByTeamHandlerTests.HandleSuceeds_TeamIdVaried_ExpectedTeamActivitiesRecordsReturned() in C:\Source\Compliance\Clarity.Processes.Api\test\Clarity.Processes.Application.Unit.Tests\v0_3\TeamActivities\Handlers\ListTeamActivitiesByTeamHandlerTests.cs:line 201

Method that requires Testing

The Unit Test is simple enough and clearly does not attempt to mock a database connection

The Unit Test

Finally FYI, Line 79 on the code calls this method - which is why a database connection is required

Sample SQL being used

So the question is, having mocked data into a database (line 198 of unit test) - how can I then use this data to test the SQL ? And can I simulate the Create Command (line 77 of code) in order to avoid the above error. Thanks.

I've read up on this but not sure how to tackle it OR if it can be done.

0

There are 0 best solutions below