Itβs easy for me to write unit tests for algorithms. For example, sort(List) , it is easy to write tests such as:
list = [2, 1, 4]; assert(sort(list) == [1, 2, 4]);
But itβs very difficult for me to test methods that have no logic, no if , just a set of calls.
Basically there are two examples that I would like to answer as unit test them:
Example 1:
Let's say I have a class that is responsible for writing some data to a file, but this data is written in a certain way by external functions ( writeHeaderToFile , writeSerializedData and writeEndOfFile ).
Data is not written directly to a file, therefore, if the data is:
{ list: [ "item 1", "item 2" ], name: "aaa" }
This does not mean that the file will not be either a simple version of this data (without spaces), or it will not be a simple serialized version or an encrypted version of the file. The actual binary will be something unknown to me. All I know is that I can use these 3 methods to write correctly.
This file also contains some other information that does not come directly from these three methods, such as a header of a certain type (which again I do not know how it will be presented in a binary file).
This is the class:
class FileCreator { populateFileWithData(File file, Data data) { doBlockWithLock(file, { Header header; header.format = SomeFormat; header.version = SomeVersion; writeHeaderToFile(file, header); writeSerializedData(file, data); writeEndOfFile(file); }); }
Example 2:
class Controller { var screenOne = new ScreenOne(); var screenTwo = new ScreenTwo(); var screenThree = new ScreenThree(); void reloadButtonWasClicked() { screenOne.reload(); screenTwo.reload(); screenThree.reload(); } }
For this, I could do something like this:
var mockScreenOne = Mock<ScreenOne>().reload.expectOneCall(); var mockScreenTwo = Mock<ScreenTwo>().reload.expectOneCall(); var mockScreenThree = Mock<ScreenThree>().reload.expectOneCall(); Controller controller = new Controller(); controller.screenOne = mockScreenOne; controller.screenTwo = mockScreenTwo; controller.screenThree = mockScreenThree; controller.reloadButtonWasClicked(); mockScreenOne.verify(); mockScreenTwo.verify(); mockScreenThree.verify();
But I donβt really appreciate it, because I simply say that I am doing the same thing as in the implementation. Sounds like repeating code to me.
What would be the correct way to test my 2 examples?