C# 单元测试API调用
我正在使用.NETCore和xUnit/Moq来创建单元测试。我想为以下API调用创建一个单元测试:C# 单元测试API调用,c#,unit-testing,asp.net-core,moq,xunit,C#,Unit Testing,Asp.net Core,Moq,Xunit,我正在使用.NETCore和xUnit/Moq来创建单元测试。我想为以下API调用创建一个单元测试: [HttpGet("{zip}")] public IActionResult Get(int zip) { //debugging here shows the repository has the object //but the result is always null Location result = repository[zip]; if(resul
[HttpGet("{zip}")]
public IActionResult Get(int zip)
{
//debugging here shows the repository has the object
//but the result is always null
Location result = repository[zip];
if(result == null)
{
return NotFound();
}
else
{
return Ok(result);
}
}
我的单元测试(失败)是:
根据在测试方法中访问的内容,在安排测试时设置了错误的成员
[Fact]
public void Api_Returns_Json_Object() {
//Arrange
int zip = 88012;
var location = new Location
{
zip = zip,
type = "STANDARD",
state = "NM"
};
Mock<IRepository> mockRepo = new Mock<IRepository>();
mockRepo.Setup(m => m[zip]).Returns(location);
var controller = new ApiController(mockRepo.Object);
// Act
var response = controller.Get(zip);
var okResult = response as OkObjectResult;
// Assert
Assert.NotNull(okResult);
Assert.Equal(location, okResult.Value);
}
[事实]
public void Api_返回_Json_Object(){
//安排
int-zip=88012;
var位置=新位置
{
zip=zip,
type=“标准”,
state=“NM”
};
Mock mockRepo=新Mock();
mockRepo.Setup(m=>m[zip])。返回(位置);
var控制器=新的ApiController(mockRepo.Object);
//表演
var response=controller.Get(zip);
var okResult=响应为OkObjectResult;
//断言
Assert.NotNull(okResult);
Assert.Equal(位置,okResult.Value);
}
IEnumerable<Location> Locations { get; }
Location this[int zip] { get; }
[Fact]
public void Api_Returns_Json_Object() {
//Arrange
int zip = 88012;
var location = new Location
{
zip = zip,
type = "STANDARD",
state = "NM"
};
Mock<IRepository> mockRepo = new Mock<IRepository>();
mockRepo.Setup(m => m[zip]).Returns(location);
var controller = new ApiController(mockRepo.Object);
// Act
var response = controller.Get(zip);
var okResult = response as OkObjectResult;
// Assert
Assert.NotNull(okResult);
Assert.Equal(location, okResult.Value);
}