|
From: Noel D. <ma...@mc...> - 2008-08-22 18:39:27
|
On Fri, 22 Aug 2008 06:57:59 +0300 "Kyohere Luke" <pr...@gm...> wrote: > I'm trying to test Class_A::Method_B(..). Method_B internally calls > Class_C::Method_D() - which takes a long time, and is accessed from > the global/autoload mechanism of the application. I'd like to skip > this call, since it's irrelevant to my tests. If class_c->method_d() is part of the logic of class_A->method_B() then it is relevant to the test. Mocking is often a good way to test object interactions but you could also use the real object. There are pros and cons to both. I usually favour mocks myself. Actually, mocks are more about design than testing (although that too). If you were coding test-first, you'd have discovered a need for class_C while writing a test for class_A, mocked it out, and then come back to implement it later. I can't recommend this way of working strongly enough. For one thing, you wouldn't be wondering how to test the class you've just written: it would already be fully-tested ;) > Aside from re-designing my class/method to read in Class_C as one of > it's arguments, or else creating a dummy Class_C, and loading it > before the real one is loaded, is there a way to achieve this with > Mocks? You probably should pass it in (either directly or via some kind of registry/container, as suggested above, and probably in that order of preference). Very often that will be the best choice - but it isn't *always* the best choice. If class_A should be responsible for instantiating class_C, the other thing you can do is to use a partial mock: (1) in class_A, refactor object instantiation into a factory method (2) knock the method out with a partial mock of class_A (3) set the method to return a reference to a mock class_C This is explained in the simplestest docs but I'll post some code if you're not sure how it works. > Secondly, is there a way to prevent the class I'm trying to test from > calling such mundane php functions like file_exists(), etc? Because > in such a case, I have to design my test to create/delete files from > the file system and so on. That's fine. Have a look at http://aperiplus.sourceforge.net/FileSystemTestCase.php. I've written some extensions for SimpleTest, and this is what I use for filesystem tests. It's not really supported and is liable to change suddenly if I think of something better but it might give you a few ideas. Pinch anything you like the look of. The expectation classes will work in a standard UnitTestCase. http://aperiplus.svn.sourceforge.net/viewvc/aperiplus/lib/simpletest/ Alternatively you could refactor the file_exists() call into a method and kill it in a partial mock, similar to above. Personally, I'd just write/unlink the files. In general, when you hit an application boundary I think that you should use the real resource. Noel |