1

Details: I Have tried a few different solutions, i don't use an interface as it is unnecessary for the service, I also have a few other methods for creating and retrieving/ updating. The error im getting is

invalid operation connection string must be initialised"System.InvalidOperationException: The ConnectionString property has not been Initialised",

i get this error when await connection.openasync() is hit, since the connection string is invalid this throws. I want to know what the best way for writing test cases for these are: Thanks.

All I'm looking to achieve is write test for my handler method, i keep getting errors with connection string not set, below is my code example. I want to write a test to confirm that the method creates an item.

My Handler Method

private readonly IMapper _mapper 
private readonly ILogger < CreateDogTrailItemCommandHandler >  _dogTrailService;
private readonly DogTrailService.DogTrailService _dogTrailService;
public CreateDogTrailCommandHandler(Imapper mapper,DogTrailService.DogTrailService dogTrailService,ILogger<CreateDogTrailItemCommandHandler> dogLogger) {
    _dogTrailService = dogTrailService;
    _mapper = mapper;
    _logger = dogLogger
}

public async Task < Unit > Handle(CreateDogTrailItemCommand request,CancellationToken    cancellationToken) {
        var dogTrailItem = _mapper.Map < DogTrail > (request.DogTrailDto);
        await _dogTrailService.AddAsync(dogTrailItem);
        return Unit.value;

My Service:

public class DogTrailService {
    private readonly string _dogTrailConnectionString;

    public DogTrailServices(IConfiguration configuration) {
    _dogTrailConnectionString = configuration.GetConnectionString("DogTrailSqlDb");
    }

    public async Task < DogTrail > AddAsync(DogTrail entity) {
     using(SqlConnection connection = new SqLConnection(_dogTrailConnectionString)) {
           await connection.OpenAsync();
           using(SqlTransaction transaction = connection.BeginTransaction()) 
    {
              string query = "INSERT INTO DogTrail ( dognumb, dogIndex) 
    VALUES ( @dognumb,   @dogindex): SELECT SCOPE_IDENTITY();";
              using(Sqlcommand command = new Sqlcommand(query, connection)) {
                 command.Parameters.AddWithValue("@dognumb, entity.dognumb); 
                    command.Parameters.AddWithValue("@dogindex, entity.dogindex);
                       entity.Id = (int)(decimal) await command.ExecuteScalarAsync();  
    transaction.Commit();
                       return entity;
            }
        }
    }
}

My Test:

[Test]
public async Task Handle_ValidRequest_AddsNewDogTrailItem() {
   // Arrange
   var mockMapper = new Mock < IMapper > ();
   var mockDogTrailService = new Mock < DogTrailService > ();
   var mockLogger = new Mock < ILogger < CreateDogTrailItemCommandHandler >> ();
   var handler = new CreateDogTrailItemCommandHandler(mockMapper.Object, 
   mockDogTrailService.Object,  mockLogger.Object);
   var request = new CreateDogTrailItemCommand(new DogTrailDto());

   var dogTrail = new DogTrail();

   mockMapper.Setup(m => m.Map < DogTrail > (It.IsAny < DogTrailDto > ())).Returns(dogTrail);

   // Act
   await handler.Handle(request, CancellationToken.None);

   // Assert
   mockMapper.Verify(m => m.Map < DogTrail > (request.DogTrailDto), Times.Once);
   mockDogTrailService.Verify(m => m.AddAsync(dogTrail), Times.Once);
}

I have tried passing in a fake connection string, but my problem is when the AddAsync Method is called it fails as openconnection is throwing as its a dummy connection.

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
LowKeyLo
  • 57
  • 8
  • please don't use headers (#) for putting emphasis on text. It's "shouty" and not nice to read. – JHBonarius May 08 '23 at 15:51
  • You need to mock _interfaces_ of the services. Not implementations. Else you'll get all the implementation details (it creates a derived class) in your test. I'll look for the dupe and tag it, this has been answered before. P.S. you should really start using Entity Framework Core or Dapper or so. – JHBonarius May 08 '23 at 15:57
  • possible dupe: [link](https://stackoverflow.com/questions/1972831/to-mock-an-object-does-it-have-to-be-either-implementing-an-interface-or-marked) – JHBonarius May 08 '23 at 16:00
  • @JHBonarius Yeah cant use EF would have been alot simpler – LowKeyLo May 08 '23 at 19:12

0 Answers0