Kevin
Kevin

Reputation: 6292

What is the purpose of unit testing at this scenario if mock is used

I have a question about unit testing. I have been thinking about it for days and could not find the answer.

Say, I have a function which download files from a web service and write it to the disk. What is the purpose of testing it without actually see the files are downloaded and write to the disk?

Although I understand we can mock out the web service, but how I can do it in this scenario? As far as I know, something like Mockito only mock the behaviour but not giving meaningful data (file in this example).

Even if we can mock the behaviour of web service, how I can mock writing a file to a disk without really writing something to the disk?

I am sorry I don't have a concrete example for this. Please feel free to give your opinion.

Many thanks

Upvotes: 3

Views: 289

Answers (2)

Kalpak Gadre
Kalpak Gadre

Reputation: 6475

I always say that unit testing your code makes it more modular, as it forces you to think how I can decouple this class and test it in isolation.

In your case when you want to test something like writing a file to disk, you can instead make your method writing the file to interact with simply an OutputStream This will ensure that you can simply pass a ByteArrayOutputStream to the function instead of actual FileOutputStream You can then get the bytes convert to String and check if the content matches to what you actually expect.

It is also possible to create a temp file and pass the FileOutputStream of the temp file to write, and subsequently you can check contents of the file.

By making the method interact with an OutputStream, you make it decoupled from process of identifying the file path, creating the FileOutputStream etc.

As you mentioned, it may not make much sense to test this function if it is simply getting data from some web service and simply writing it to the file. But it would be interesting to test it in case it manipulates the data intelligently or is expected to do something when the web service interaction throws an exception.

Upvotes: 5

k.m
k.m

Reputation: 31464

Say, I have a function which download files from a web service and write it to the disk. What is the purpose of testing it without actually see the files are downloaded and write to the disk?

There is none. You don't test that with unit testing. In such cases (interactions with network, file system, database) you write integration tests. They often utilize similar tools and frameworks to unit tests, but they serve different purpose - to test your components integration and interactions between them. Integration tests often mimic your application real-world usage.

If all your function does is call one service/component to download file and another one to save it to disk, then unit testing is rather limited in this case.

Upvotes: 4

Related Questions