Hello i am writing a lot of test to test negative scenarios so basically when a task fails i need to check that the right exception type is thrown and that the message is right. What i have tried by googling is this
public async void TaskToTest_OnFailGiveException()
{
var info = new Info();
var ex = await Record.ExceptionAsync(() => info.TaskToTest());
Assert.NotNull(ex);
Assert.IsType<Exception>(ex);
}
As well as this to test the message
public void TaskToTest_OnFailGiveException()
{
var info = new Info();
var ex = Assert.ThrowsAsync<Exception>(() => info.TaskToTest());
Assert.NotNull(ex.Exception);
Assert.Equal(ex.Exception.Message, $"Failed to insert the info");
}
The problem with both of them is that the task doesn't fail so by there it doesn't give any exception to assert against. I know that if i want to mock that a task gives positive return i can to info.TaskToTest().Returns(Task.CompletedTask)
but i have failed to find a fail variant of it. Is there any way to make sure that a task fails so i can test teh exception?
This is the task i try to make fail
public virtual async Task TaskToTest()
{
bool result = await _database.InsertOrUpdateInfo(State.InfoID, _unhandledInfo.Count > 0 ? JsonConvert.SerializeObject(_unhandledInfo) : string.Empty);
if (!result)
{
_logger.LogError($"Error while calling InsertOrUpdateInfo. Info: {State.INfoID}");
var exception = new Exception("Failed to insert the info");
throw exception;
}
}
Aucun commentaire:
Enregistrer un commentaire