Unit testing code that basically does perseverance - Should I worry?

I am using api which interacts with db. This api has methods for querying, loading and saving items in db. I wrote integration tests that do things such as creating a new instance, and then check that when I make a request for this instance, the correct instance is found. Everything is good.

I would like to have faster unit tests for this code, but I wonder about the usefulness of any unit test, and if they really give me anything. for example, lets say that I have a class to save some element that I have through the API. This is the psuedo code, but get an idea of ​​how the api that I use works.

public class ElementSaver { private ITheApi m_api; public bool SaveElement(IElement newElement, IElement linkedElement) { IntPtr elemPtr = m_api.CreateNewElement() if (elemPtr==IntPtr.Zero) { return false; } if (m_api.SetElementAttribute(elemPtr,newElement.AttributeName,newElement.AttributeValue)==false) { return false; } if (m_api.SaveElement(elemPtr)==false) { return false; } IntPtr linkedElemPtr = m_api.GetElementById(linkedElement.Id) if (linkedElemPtr==IntPtr.Zero) { return false; } if (m_api.LinkElements(elemPtr,linkedElemPtr)==false) { return false; } return true; } } 

Should I write block tests that mock the m_api element? it seems that I can verify that if any of the different calls fail, a false is returned, and that if all the different calls are successful, true is returned, and I could set the expectation that the various methods are called with the expected parameters, but is it useful? If I had to reorganize this code to use several slightly different api methods, but achieve the same result, this would break my tests, and I would need to change them. This fragility does not seem very useful.

Should I worry about hardware tests for such code, or should I just stick to the integration tests I have?

+4
source share
2 answers

See what tests are. If you are only checking to see if material that comes into the database, etc. You are probably doing the right thing only by doing automatic integration tests. If there is logic that you want to test, you might want to see if you can decompose your logic into separate classes that you can unit test and facades around infrastructure code that do not contain logic.

+4
source

This is a good idea to mock m_api in my code for the following reasons (not all of which apply to your psuedo-code example):

  • As you mentioned, you can make sure your class performs error handling correctly
  • In cases where you have more complex code in your class (for example, caching), you can use the expectations for your layout to make sure that the class behaves correctly. For example, get the same object twice, but make sure m_api is called only once.
  • Your unit test can test the behavior without creating an appropriate dataset. This increases maintainability over time as the data model changes under m_api.
+2
source

All Articles