测试以下控制器
public class AnnouncementController : Controller
{
IConfiguration _configuration;
IHostingEnvironment _env;
ILoggerManager _logger;
public AnnouncementController(IConfiguration configuration, IHostingEnvironment env, ILoggerManager logger)
{
_configuration = configuration;
_env = env;
_logger = logger;
}
[HttpGet ("{employeeID}/{moduleID}")]
public ActionResult<Announcements> GetAnnouncements([FromRoute]int employeeID, [FromRoute] int moduleID)
{
try
{
Services.Interface.IAnnouncementService service = new Services.Imp.AnnouncementService(_configuration, _logger);///establishing new Service connection
if (service != null)
{
Announcements announcements = service.GetAnnouncements(employeeID, moduleID);
return announcements;
}
else
{
return BadRequest("Unable to establish connection.");
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message, ex);//log error
return BadRequest(ex.Message);
}
}
}
使用以下测试代码:
public void ForSessionActionResult_ReturnsObjectResult()
{
IConfiguration _configuration;
IHostingEnvironment _env;
ILoggerManager _logger;
var mock_logger = new Mock<ILoggerManager>();
_logger = mock_logger.Object;
var mock_configuration = new Mock<IConfiguration>();
_configuration = mock_configuration.Object;
var mock_env = new Mock<IHostingEnvironment>();
_env = mock_env.Object;
var sut = new AnnouncementController(_configuration, _env, _logger);
int employeeID = 1;
int moduleID = 1;
var result = sut.GetAnnouncements(employeeID, moduleID);
var actionResult = Assert.IsType<ActionResult<Announcements>>(result);
Assert.IsType<NotFoundObjectResult>(actionResult.Result);
}
我在BadRequestObjectResult
上的Assert.IsType NotFoundObjectResult
上正在被测试的控制器上。
我不确定是否正确地模拟了控制器构造函数。
但是在上次声明中我得到了BadRequestObjectResult
。