1

I need to mock this C# WebApi class using the Moq framework

   public class PvValuesController
    {
        private readonly IDataServices dataService;

        public PvValuesController(IDataServices dataServices)
        {
            dataService = dataServices;
        }

        [HttpGet]
        public IHttpActionResult Get(string id, string st, string et)
        {
            if (dataService == null)
            {
                return BadRequest("DataService not found");
            }

            var result = dataService.GetPvData(id, st, et);   
            return Ok(result);
        }
    }

Problem is, if I mock it like this:

var controllerMock = new Mock<PvValuesController>();

I'm not passing any DataService to it, so the Get() function will always return a bad request code.

The original line was:

var controller = new PvValuesController(dataService);

Where dataService is a concrete instance of IDataService and is a complex object

How can I effectively mock such class?

EDIT:

my new test code:

[Test]
public async void TestMoq()
{
    var a = new List<dynamic>();
    a.Add(23);

    // arrange
    var dataService = new Mock<IDataServices>();
    dataService.Setup(l => l.GetPvData(It.IsAny<string>(), It.IsAny<DateTime>(), It.IsAny<DateTime>())).Returns(a);
    var controller = new PvValuesController(dataService.Object);

    // act
    var actionResult = controller.Get("groupid", "timestampstart", "timestampend");
    var httpResponseMessage = await actionResult.ExecuteAsync(CancellationToken.None);

    // assert
    Assert.AreEqual(HttpStatusCode.BadRequest, httpResponseMessage.StatusCode);
}

I get an exception on the await line:

System.InvalidOperationException: HttpControllerContext.Configuration must not be null

Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159
  • 1
    You have to mock the `IDataServices` not the Controller – Karthik Aug 12 '15 at 10:24
  • ok your're right. I tried but the original dataService is created like this: var dataService = new DataServices(importer, consumer, null, null, uhhElasticUtility); I need many "real" objects in order to mock it – Gianluca Ghettini Aug 12 '15 at 10:28

1 Answers1

1

Mock your dependency interface as shown below

var service = new Mock<IDataServices>();

Inject it to your controller

var ctrlObj = new PvValuesController(service.Object);

Then continue with your setup as usual for the service

service.SetUp(l => l.Get()).Returns("Hello World!!!");

Finally call your controller method using the controller instance

ctrlObj.Get("A","B","C");
Karthik
  • 1,064
  • 2
  • 16
  • 33