简体   繁体   中英

Mocking a context using Moq

Upon debugging a request, I see that the object type passed to is of type Microsoft.AspNetCore.Http.DefaultHttpContext which I'm trying to mock here in a unit test, which for some reason is not instantiable.

screenshot:
截屏 https://i.stack.imgur.com/Hag1d.png

 app.Run(async context =>
 {

 });

Unit test

var contextMock = new Mock<Microsoft.AspNetCore.Http.DefaultHttpContext>();

error:
错误

在此处输入图像描述

No need to mock that class.

You can create an instance of DefaultHttpContext

HttpContext context = new DefaultHttpContext();
context.Request.Path = new PathString("path here");

//...

or just mock HttpContext is you want to mock specific features.

Mock<HttpContext> contextMock = new Mock<HttpContext>();

//...setup
var path = new PathString("path here");
contextMock.Setup(_ => _.Request.Path).Returns(path);

HttpContext context = contextMock.Object;

The former is simpler and requires very little setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM