我正在开发一个单元测试项目来测试Web API v2,其中IHttpActionResponse
为返回类型。
我无法找到使用IHttpActionResponse
返回类型测试所有状态代码的方法。特别是帖子需要测试创建的http状态代码。在这里,我还为Get
和GetById
创建了一些测试。让我知道如何测试返回IHttpActionResponse
的所有状态代码。
API控制器代码
public class StudentController : ApiController
{
IRepository<Student> repository;
ITransformers<StudentModel, Student> transformer;
public StudentController(IRepository<Student> studentRepository, ITransformers<StudentModel, Student> studentTransformer)
{
repository = studentRepository;
transformer = studentTransformer;
}
[HttpGet]
public IHttpActionResult Get()
{
IEnumerable<Student> students = null;
try
{
students = repository.Get();
if (students.Count<Student>() > 0)
{
return Ok(students);
}
else
{
return StatusCode(HttpStatusCode.NoContent);
//return Content(HttpStatusCode.NoContent, students);
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpGet]
public IHttpActionResult Get(int Id)
{
Student student = null;
try
{
student = repository.GetById(Id);
if (student != null)
{
return Ok(student);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPost]
public IHttpActionResult Post(StudentModel studentModel)
{
try
{
Student student = transformer.TransformModelToEntity(studentModel);
int result = repository.Save(student);
if (result > 0)
{
student.Id = result;
return Content(HttpStatusCode.Created, student);
}
else
{
return InternalServerError();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPut]
public IHttpActionResult Put(StudentModel studentModel)
{
try
{
Student student = transformer.TransformModelToEntity(studentModel);
if (repository.Update(student))
{
return Content(HttpStatusCode.Accepted, studentModel);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpDelete]
public IHttpActionResult Delete(int Id)
{
try
{
if(repository.Delete(Id))
{
return Ok();
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
我的测试类代码
[TestClass]
public class StudentServiceTest
{
static Mock<ITransformers<StudentModel, Student>> mockTransformer;
static Mock<IRepository<Student>> mockRepository;
[ClassInitialize]
public static void ClassInit(TestContext context)
{
mockTransformer = new Mock<ITransformers<StudentModel, Student>>();
mockRepository = new Mock<IRepository<Student>>();
}
//GetAll Tests
[TestMethod]
public void GetReturnsAllStudents()
{
// Arrange
IEnumerable<Student> fakeStudents = GetFakeStudents();
mockRepository.Setup(x => x.Get()).Returns(fakeStudents);
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get();
var contentResult = actionResult as OkNegotiatedContentResult<IEnumerable<Student>>;
// Assert
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
Assert.IsInstanceOfType(contentResult, typeof(OkResult));
Assert.AreEqual(3, contentResult.Content.Count());
}
[TestMethod]
public void GetReturnsNoContent()
{
// Arrange
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get();
StatusCodeResult statusCodeResult = actionResult as StatusCodeResult;
//Assert
Assert.IsNotNull(statusCodeResult);
Assert.AreEqual<HttpStatusCode>(HttpStatusCode.NoContent, statusCodeResult.StatusCode);
}
[TestMethod]
public void GetReturnsException()
{
// Arrange
mockRepository.Setup(x => x.Get()).Throws<Exception>();
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get();
//Assert
Assert.IsNotNull(actionResult);
Assert.IsInstanceOfType(actionResult, typeof(ExceptionResult));
}
//End of tests GetAll
//GetById Tests
[TestMethod]
public void GetByIdReturnsStudent()
{
// Arrange
IEnumerable<Student> fakeStudents = GetFakeStudents();
mockRepository.Setup(x => x.GetById(It.IsAny<int>())).Returns(fakeStudents.FirstOrDefault());
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get(It.IsAny<int>());
var contentResult = actionResult as OkNegotiatedContentResult<Student>;
// Assert
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
Assert.AreEqual(1, contentResult.Content.Id);
}
[TestMethod]
public void GetByIdReturnsNotFound()
{
// Arrange
Student student = null;
mockRepository.Setup(x => x.GetById(It.IsAny<int>())).Returns(student);
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get(It.IsAny<int>());
// Assert
Assert.IsNotNull(actionResult);
Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
}
[TestMethod]
public void GetByIdReturnsException()
{
// Arrange
mockRepository.Setup(x => x.Get()).Throws<Exception>();
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Get(It.IsAny<int>());
//Assert
Assert.IsNotNull(actionResult);
Assert.IsInstanceOfType(actionResult, typeof(ExceptionResult));
}
//End of GetById tests
}
检查状态代码201的测试帖子
[TestMethod]
public void PostReturnsSuccess()
{
// Arrange
mockRepository.Setup(x => x.Save(It.IsAny<Student>())).Returns(1);
mockTransformer.Setup(x => x.TransformModelToEntity(It.IsAny<StudentModel>())).Returns(GetFakeStudents().FirstOrDefault());
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Post(It.IsAny<StudentModel>());
var createdResult = actionResult as CreatedNegotiatedContentResult<Student>;
//var createdResult = actionResult as CreatedAtRouteNegotiatedContentResult<Student>;
//Assert
Assert.IsNotNull(actionResult);
Assert.IsNotNull(createdResult.Content);
Assert.AreEqual(1, createdResult.Content.Id);
}
尝试使用CreatedNegotiatedContentResult
和CreatedAtRouteNegotiatedContentResult
并比较状态代码,但我的actionResult
对Formatters,ContentNegotiation和Request Properties有例外,并在createdResult
中获取一个空对象。
让我知道如何检查状态代码201?
更新了从CustomFilter
模拟BadRequestModelstatevalidationfilter
public class ModelStateValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
BadRequest的测试方法
[TestMethod]
public void PostReturnsBadRequest()
{
// Arrange
//var mockFilter = new Mock<ModelStateValidationFilter>().Setup(x=>x.OnActionExecuting(It.IsAny<HttpActionContext>()))
var controller = new StudentController(mockRepository.Object, mockTransformer.Object);
// Act
IHttpActionResult actionResult = controller.Post(new StudentModel { Id = 0, FirstName = "Raju", LastName = "", CourseId = 0 });
var badResult = actionResult as NegotiatedContentResult<Student>;
//Assert
Assert.IsNotNull(actionResult);
Assert.IsInstanceOfType(actionResult, typeof(BadRequestErrorMessageResult));
//TODO: Check for status code bad request and
Assert.IsNotNull(badResult.Content);
Assert.AreEqual(HttpStatusCode.Created, badResult.StatusCode);
}
其中in model lastname是必需的,因此API返回BadRequest。但是如何在单元测试中模拟这种行为?