Kumar AU

Kumar AU

  • 1.4k
  • 309
  • 60k

How to mock the request Object in Controller using NUnittest class

Jun 28 2023 1:44 AM

Please let me know How do I Mock my "HttpRequestMessage" object so that when my code flows traverse from nUnitTest it should not having NULL value for "this,Request,CreateResponse()".

My Controller class:

public class EodController : ApiControllerBase
{
private readonly IEodManager eodManager;

public EodController(IEodManager, eodManager)
{

this.eodManager = eodManager;
}

/// <param name="executionDate">Execution date</param>
/// <returns>Returns <see cref="HttpResponseMessage"/> that contains a stream of JSON data.</returns>
[HttpGet]
[Route("")]
public async Task<HttpResponseMessage> GetCheckAsync([Fromuri] DateTime executionDate)
{

try

{

int Status = await this.eodManager.GetStatus(executionDate);

will be always NULL value

var response = this.Request.CreateResponse(); // It failed Here "this.Request’ will be always NULL value
response.StatusCode = (Status == 1) ? HttpStatusCode.OK : (HttpStatusCode)207;

response. Content =
new PushStreamContent(
(stream, httpContext, transportContext) => this.eodManager.WriteToStream(stream, criteria, Status),

I have Tried following things from test Class, it did not work .

public async Task ShouldReturnOKStatus()
{

// Arrange
// Set up the mock

var EodManager, = new Mock<IEodManager>();
DateTime executionDate = new Datelime(2023, 6, 27);

var data = "this will be JSON”;
var httpReguestMessage = new HttpRequestMessage();

httpRequestMessage Content= new StringContent(data, Encoding.UTF8, “application/json");

var command = new EodController(EodManager.Object); // Act

var response = await command.GetCheckAsync(executionDate);
Assent.AreEqual("System.Web.Http.Results.OkResult”, response.ToString());
}

 


Answers (5)