简体   繁体   中英

Unit Test C# Can we test catch block?

let's say i have a method that logins in;

public async Task<IActionResult> Login()
{
    try
    {
        //my codes..
    }
    catch(Exception exp)
    {
        _sLogger.Slack(exp)
        return BadRequest();
    }
}

i have tested all controllers and methods but i can't test the catch block? i can't throw a exception, how can i do that?

i have tried like this but that doesn't work for me:

public void_WithInvalidData_ThenBadRequest()
{
    authController.UnAuthrorize();
    var result=(BadRequestResult)authController.Login();
    Assert.True(result.StatusCode == (int)HttpStatusCode.BadRequest);
    authController.Authorize();
}

Use following code

public async Task<IActionResult> Login()
{
    try
    {
       if (conditions) throw new Exception($"Message"); // throw an exception
    }
    catch(Exception exp)
    {
        _sLogger.Slack(exp)
        return BadRequest();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM