Skip to content

Unable to mock mediator in controller test #72

Closed
@adnancindioglu

Description

@adnancindioglu
[Authorize]
[Route("[controller]")]
[ApiController]
public class BaseApiController : Controller
{
 private IMediator _mediator;
 protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

I don't have constructor to mock mediator so i can't set my result value.
Transactions in "GetBankImageQuery" return null or false.

[ApiController]
public class BankImagesController : BaseApiController
{
        [HttpGet("getByBankId")]
        public async Task<IActionResult> GetByBankId(long bankId)
        {
            var result = await Mediator.Send(new GetBankImageQuery { BankId = bankId });
           
            if (!result.Success)
            {
                return BadRequest(result.Message);
            }
            return File(result.Data.Image, result.Data.ContentType);
      
        }
}

Unit test example in architecture:


[Test]
public async Task BankImages_GetByBankId_Success()
{
    const string requestUri = "api/BankImages/getByBankId?bankId=1";
    string token = MockJwtTokens.GenerateJwtToken(ClaimsData.GetClaims());

    var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri);
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var response = await HttpClient.SendAsync(requestMessage);

    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}

How should I proceed here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions