【发布时间】:2016-06-12 00:40:09
【问题描述】:
我有一个 ActionResult,它在带有 EntityFramework 和 Epplus 的 MVC 5 项目中始终如一地工作。单击视图上的操作链接会触发此 ActionResult,它将所选模型发送到新的 Excel 文档。
我正在学习在 Visual Studio 2013 中对我的 MVC 代码进行单元测试(使用 Nuget Xunit 包),并认为我将从小处着手,在通过断言 ActionResult 不为空来实现 ActionResult。
测试失败,回复如下:"System.InvalidOperationException : No connection string named 'StudentContext' could be found in the application config file."
我了解错误消息的含义,但我的问题是如何在测试项目中正确定义控制器上下文。我是否遗漏了一些简单明了的东西,比如定义一个上下文变量,还是我完全错误的方式?
这是我用来测试 ActionResult 的代码块。
using StudentProject.Controllers;
using System.Web.Mvc;
using Xunit;
namespace StudentProject.Tests.Controllers
{
public class StudentRosterControllerTest
{
[Fact]
public void ExportToExcel_IsNotNull()
{
// Arrange
StudentRostersController controller = new StudentRostersController();
ActionResult ExcelExport;
// Act
ExcelExport = controller.ExportToExcel();
// Assert
Assert.NotNull(ExcelExport);
}
}
}
这是我正在测试的代码。它是一个自动脚手架控制器,隐藏了自动生成的 crud 方法,显示了要测试的单个方法。
using OfficeOpenXml;
using StudentProject.Models;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace StudentProject.Controllers
{
public class StudentRostersController : Controller
{
private StudentContext db = new StudentContext();
// Auto-scaffolded CRUD methods not shown
// This ActionResult exports the StudentRoster model
// to a fresh Excel file.
public ActionResult ExportToExcel()
{
IEnumerable<StudentRoster> query = db.StudentRosters.AsEnumerable();
using (var excelFile = new ExcelPackage())
{
ExcelWorksheet worksheet =
excelFile.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].LoadFromCollection(Collection: query,
PrintHeaders: true);
// Results in file downloaded to user's default
// "My Downloads" folder.
return File(excelFile.GetAsByteArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Export.xlsx");
}
}
}
}
【问题讨论】:
标签: c# asp.net-mvc unit-testing tdd xunit