So I have two classes:
1. get data (html) from url, url is static (can't be set)
2. parses data from html
So how can I test it?
Thanks for any help
Moderator: General Moderators
Write your ownarjan.top wrote:a.) but how am I supposed to get html to parse?
Code: Select all
public function testHyperlinksAreParsed() {
$html = 'This is HTML with <a href="http://foo.bar/path/?q=v">link one</a> and ' .
'<a class="test" href="http://www.test.com/">link two</a> in it.';
$parser = new HtmlParser();
$parser->parse($html);
//make assertions here
$this->assertEqual(array('http://foo.bar/path/?q=v', 'http://www.test.com/'),
$parser->getHyperlinks());
}Code: Select all
interface Document {
public function getHtml();
}Code: Select all
class RemoteDocument implements Document {
private $_url;
public function __construct($url) {
$this->_url = $url;
}
public function getHtml() {
return file_get_contents($this->_url);
}
}Code: Select all
Mock::generate('Document', 'MockDocument');
class HtmlParserTest extends UnitTestCase {
public function testParsingHyperlinks() {
$html = 'This is HTML with <a href="http://foo.bar/path/?q=v">link one</a> and ' .
'<a class="test" href="http://www.test.com/">link two</a> in it.';
$document = new MockDocument();
$document->setReturnValue('getHtml', $html);
$parser = new HtmlParser($document);
//make assertions here
$this->assertEqual(array('http://foo.bar/path/?q=v', 'http://www.test.com/'),
$parser->getHyperlinks());
}
}Code: Select all
class HtmlParserTest extends UnitTestCase {
public function testParsingHyperlinks() {
$context = new Yay_Mockery();
$html = 'This is HTML with <a href="http://foo.bar/path/?q=v">link one</a> and ' .
'<a class="test" href="http://www.test.com/">link two</a> in it.';
$document = $context->mock('Document');
$context->checking(Yay_Expectations::create()
-> atLeast(1)->of($document)->getHtml() -> returns($html)
);
$parser = new HtmlParser($document);
//make assertions here
$this->assertEqual(array('http://foo.bar/path/?q=v', 'http://www.test.com/'),
$parser->getHyperlinks());
$context->assertIsSatisfied();
}
}Roughly speaking yes. I still try to focus them as much as possible, but I don't worry so much about external dependencies.b.) so acceptance test is just set of operations tested at once?
That's what we call "tight coupling" and something which hinders unit testing. Using a registry can help since you can mock the registry to return a mock object. Other solutions are to pass in a factory object (which can be mocked) or to use dependency injection extensively. I admit, this is one of the places I let myself slide sometimes when I'm in a hurry to get something written.arjan.top wrote:Ok it works great now![]()
But what if class is instantiated inside a method? Any way to "fake" return values of that object?