Unit test saving/retrieving object

c#, unit-testing

Solution

You noted yourself that unit-tests ought to test one thing at a time. And yet here you're testing two things - storage and retrieval.

If you want to test your service layer for handling persistence correctly, mock the persistence object (repository), and then call service methods to add object - verifying that appropriate methods on repository were called. The same for retrieval.

The main issue is whether:

you are implementing a persistence library. If yes, you should of course test peristence methods, using mock objects that will fake OS calls to file system operations.

you want to test your persistence methods (as your example suggests), but they are using 3rd party library. It doesn't make sense for unit-tests - this is the part when integration testing plays its role.

Briefly speaking - unit test tests a single unit - a "module" of your code separately from other modules. Other parts are being mocked for the purpose of verifying only the code of the unit being tested.

Integration test on the other hand tests a group of modules working together. Often integration tests are implemented to tests typical use cases of your whole system, sometimes they are used for regression testing of only a group of modules for example. There are many possibilities, but the point is that modules are being tested working together - hence integration.

Problem

Haven't really used much unit testing before, but read up on it a bit and got the idea that you really only should test 1 thing at a time. But how to do this in a nice way when for example saving and retrieving an object? I can't see that the save worked without using the "retrieve" function. And can't test the retrieve without saving something. At the moment I tried something like this... How can I assure that my test can know which one is not working? ``` [TestMethod] public void TestSaveObject() { TestStorage storage = new TestStorage(); ObejctToSave s1 = new ObejctToSave {Name = "TEST1"}; ObejctToSave s2 = new ObejctToSave { Name = "TEST2" }; storage.SaveObject(s1); storage.SaveObject(s2); List<ObjectToSave> objects = storage.GetObjects(); Assert.AreEqual(2, objects.Count); Assert.AreEqual("TEST1", objects[0].Name); Assert.AreEqual("TEST2", objects[1].Name); } ```

Original source