Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing and External Resources

I'm kind of new to unit testing, but I've recently seen how it can be quite useful. I've seen that most unit tests are self running. In fact most unit testing frameworks provide a way of running several tests at once (such as unit testing a whole system).

I wonder though; How do you deal with external resources in self running unit tests? I like the idea of testing a whole system and seeing which classes failed, but a class may, for example, create thumbnails from an uploaded image. How would that test be self running when it relies on an upload image? Would I keep a directory of images, and "pretend" to upload one of them in the test?

Any thoughts on the matter would be greatly appreciated.

like image 456
mellowsoon Avatar asked May 04 '26 11:05

mellowsoon


2 Answers

If you are planning on testing external resources then it would be integration testing. In pure unit testing -> to test external resources, you would have to mock the external resource. So in this case you create a IDirectory interface and then use say a FakeDirectory class and then use FakeDirectory to "Upload" the image. And when you are actually using the application you would pass an actual directory.

In integration testing, you could have a setup class which would do all the work to set up and then you would test.

like image 131
Prashant Avatar answered May 07 '26 00:05

Prashant


I have come across this same situation while unit testing my PHP classes. There are functions which can be tested without using any other resources (unit testing), but many functions perform file read/write operations or require database access (integration testing). In order to test these functions, I've combined unit testing with integration testing. In my setUp and tearDown testing classes, it may load a database schema or fetch test data from a local test_data/ directory required by the class functions.

like image 29
Trevor Avatar answered May 07 '26 01:05

Trevor