使用try / catch时单元测试失败

时间:2016-04-16 16:02:05

标签: c# unit-testing

我需要测试确切的Argument Exception是谨慎的。是否真的可以理解方法中的异常是警告吗?

    public JsonResult Create(TeamViewModel teamViewModel)
    {
        JsonResult result = null;
            try
            {
                // here exception throws
                var domainTeam = teamViewModel.ToDomain();
                  ...
            }
            catch (ArgumentException ex)
            {
                this.ModelState.AddModelError(string.Empty, ex.Message);
                result = this.Json(this.ModelState);
            }           

        return result;
    }

我的单元测试此方法:

 public void Create_InvalidTeamAchievements_ArgumentExceptionThrown()
 {
    Exception exception = null;
    string invalidAchievements = CreateInvalidTeamAchievements();

    // Arrange
    var viewModel = new TeamMvcViewModelBuilder().WithAchievements(invalidAchievements).Build();
    var sut = _kernel.Get<TeamsController>();

    // Act
    try
    {
        sut.Create(viewModel);
    }
    catch (ArgumentException ex)
    {
        exception = ex;
    }

    // Assert
    VerifyExceptionThrown(exception, string.Format(Resources.ValidationTeamAchievements, 
                Constants.Team.MAX_ACHIEVEMENTS_LENGTH));
}

1 个答案:

答案 0 :(得分:6)

您正在以错误的方式对其进行测试。应该测试功能以不抛出异常,因为您已经在Create Method中捕获了异常。相反,如果在JsonResult方法中引发异常,则应该断言包含ModelState的{​​{1}}应该包含错误。