2

I want to write an integration tests, but I don't know how to make an Mediator instance. I saw examples using AutoFac, but I question how to do it myself.

Maybe this is not the way to go, but it's something I want anyway. Feel free to give feedback.

So I have a constructor in my controller like this:

FooController(IMediator mediator){
}

My test is like this:

FooControllerTest(){
  var mediator = ____ //this I don't get
  var controller = new FooController(mediator);

  //do testing stuff here
}

I've tried to create the mediator like this:

var mediator = new Mediator(new ServiceFactory());

But the ServiceFactory needs a System.Type object. I tried to make a test instance of this type like this:

class TypeTestInstance : Type {}

And then the test:

FooControllerTest(){
  var mediator = new Mediator(new ServiceFactory(new TypeTestInstance()));
}

But in this example it gives an error method name expected, Stackoverflow says i need to do it like this: new ServiceFactory(() => new TypeTestInstance()); but that doesn't work. It says Delegate ServiceFactory does not take 0 arguments. But then in this example I'm not even sure if it works or not.

So I'd like to hear how you solve this..

SaloméCodes
  • 57
  • 1
  • 9

1 Answers1

1

I am not sure if you are using an API using .NET Core but this answer may help Unit testing validation through MediatR PipelineBehavior.

Using testserver to hit the HTTP endpoint also tests any mediatr handlers that are being called and you can assert whatever things make your tests reasonable (has db stored a value, is response status x, does response contain x etc)

PaulD
  • 206
  • 1
  • 5