我有一个我在Visual Studio 2017中构建的asp.net核心2.0项目。我正在学习测试asp.net核心项目的绳索,但我想知道如何测试我的HHTPGET方法控制器。
下面是我的初始控制器。
public class ValuesController : Controller
{
private Config MyConfig { get; }
private Solr Solr { get; }
private Voyager Voyager { get; }
private Messages Messages { get; }
public ValuesController(Config config, Solr solr, Voyager voyager, Messages messages)
{
MyConfig = config;
Solr = solr;
Voyager = voyager;
Messages = messages;
}
// GET api/values
[HttpGet]
[Route("/api/[Controller]")]
public IEnumerable<string> Get()
{
string version = ".NET Framework: " + Environment.Version.ToString();
string vers = "ASP.NET Core Framework: " + typeof(Controller).Assembly.GetName().Version.ToString();
return new string[] { version, vers };
}
[HttpGet]
[Route("/api/[Controller]/config")]
public JsonResult GetConfig()
{
return new JsonResult(MyConfig);
}
[HttpGet]
[Route("/api/[Controller]/solr")]
public JsonResult GetSolr()
{
return new JsonResult(Solr);
}
[HttpGet]
[Route("/api/[Controller]/voyager")]
public JsonResult GetVoyager()
{
return new JsonResult(Voyager);
}
[HttpGet]
[Route("/api/[Controller]/messages")]
public JsonResult GetMessages()
{
return new JsonResult(Messages);
}
只是想知道是否有人可以举例说明如何测试这些路由或HTTPGets ......
答案 0 :(得分:1)
所以我发现第一步是设置一个通用的模拟连接,所以我创建了一个方法来通过下面的方法模拟与服务器的连接。
private CollectionsController SetupController()
{
if (controller != null)
{
controller = null;
}
if (controllerContext != null)
{
controllerContext = null;
}
controller = new CollectionsController();
controller.ControllerContext = new ControllerContext();
controllerContext = controller.ControllerContext;
controllerContext.HttpContext = new DefaultHttpContext();
//The header below is generic don't really care what the device id is
controllerContext.HttpContext.Request.Headers["device-id"] = "20317";
}
然后作为一个例子,我在下面设置了一个测试,只检查状态代码并断言从控制器返回的对象不为空。
[Fact]
public void TestPostCollectionName()
{
valData = new ValData();
valData.value = "NewObject";
controller = SetupController();
var results = controller.PostCollectionName(valData, testCollecName);
Assert.NotNull(results);
Assert.True(controllerContext.HttpContext.Response.StatusCode == 200);
}