How to use Throws() here...

5 posts, 0 answers
  1. James Legan
    James Legan avatar
    54 posts
    Member since:
    Sep 2008

    Posted 18 Sep 2012 Link to this post

    I have a method that uses an OpenAccess model. I want to mock out an OptimisticVerificationException in the first (and only first) call to SaveChanges(). How can this be achieved?

    public void ThrowTest(Guid id, string stringToUpdate)
           {
               var user = _model.Users.SingleOrDefault(p => p.Guid == id);
               if (user != null)
               {
                   user.StringToUpdate = stringToUpdate;
                   try
                   {
                       _model.SaveChanges();
                   }
                   catch (OptimisticVerificationException optimisticVerificationException)
                   {
                       _model.Refresh(RefreshMode.OverwriteChangesFromStore, user);
                       user.StringToUpdate = stringToUpdate;
                       _model.SaveChanges();
                   }
     
               }
           }
  2. James Legan
    James Legan avatar
    54 posts
    Member since:
    Sep 2008

    Posted 18 Sep 2012 Link to this post

    Here is the solution:

    // Handles the first call
    Mock.Arrange(() => _mockModel.SaveChanges()).Throws<OptimisticVerificationException>(string.Empty).InSequence();
     
    // Handles the second call.
    Mock.Arrange(() => _mockModel.SaveChanges()).InSequence();
  3. DevCraft R3 2016 release webinar banner
  4. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 21 Sep 2012 Link to this post

    Hi James,
    Thanks again for contacting us. It's great that you got the solution. However, you can also do specific Throws for different arguments.

    Kind Regards
    Mehfuz
    the Telerik team

    Time to cast your vote for Telerik! Tell DevPro Connections and Windows IT Pro why Telerik is your choice. Telerik is nominated in a total of 25 categories.

  5. James Legan
    James Legan avatar
    54 posts
    Member since:
    Sep 2008

    Posted 21 Sep 2012 Link to this post

    Mehfuz,

    Given my example, could you please provide an example of how the calls could be changed? 

    Thanks,

    Jim
  6. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 26 Sep 2012 Link to this post

    Hi James,

    It’s great that you asked the question. However, you are right. I haven't noticed that SaveChanges is a void method. In that regard InSequence is the answer.


    Kind Regards
    Mehfuz
    the Telerik team

    Time to cast your vote for Telerik! Tell DevPro Connections and Windows IT Pro why Telerik is your choice. Telerik is nominated in a total of 25 categories.

Back to Top
DevCraft R3 2016 release webinar banner