Bug
Bug

Reputation: 942

Entity Framework make Save method to fail

I have a simple entity and trying to make fail the save method for my unit test. The question is, how can I make the save method to fail and return false?

public class Sampple
{
    public int Id { get; set; }
    public string Name{ get; set; }
}

public bool Save()
{
    return (_applicationDbContext.SaveChanges() >= 0);
}

Upvotes: 0

Views: 406

Answers (1)

PontiusTheBarbarian
PontiusTheBarbarian

Reputation: 1030

Like @Yohannis said, dont waste your time testing EF itself.

If you are looking to test what might happen if a dbcontext.SaveChanges() failed, whether that be for an incorrectly parsed property or whatever.

try something like this:

`try {
   //_applicationDbContext.SaveChanges() 
  throw new Exception();

  // Remember to replace _applicationDbContext.SaveChanges() with 
  //'new Exception' when you are outside of the development db
  return(true); //whilst exception active, here is not hit
}
catch (Exception e) {
  //Error handling here
  return(false);
}`

A try catch will try to complete a process, if it cant, the catch will 'catch' the thrown exception. In our case we have purposely thrown anew Exception so that we can see exactly what would happen if _applicationDbContext.SaveChanges() did fail. I have included a very basic Exception but there are many types that you can use and tailor to exactly what kind of error you might want to test for.

I have included a link with some relatively simple examples for your consideration.

https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

Upvotes: 2

Related Questions