मैं मॉकरी के साथ मॉक इलॉक्वेंट मॉडल की कोशिश कर रहा हूं। मॉडल के माध्यम सेखोज के साथ विलुप्त मॉडल का मज़ाक उड़ाते हुए()
__construct(Post $model){$this->model=$model}
नियंत्रक में इंजेक्ट किया जाता है किया जा रहा अब मैं नियंत्रक
$post = $this->model->find($id);
में find()
समारोह बोल रहा हूँ और यहाँ PostsController
class PostsTest extends TestCase{
protected $mock;
public function setUp() {
parent::setUp();
$this->mock = Mockery::mock('Eloquent', 'Posts'); /*According to Jeffrey Way you have to add Eloquent in this function call to be able to use certain methods from model*/
$this->app->instance('Posts', $this->mock);
}
public function tearDown() {
Mockery::close();
}
public function testGetEdit()
{
$this->mock->shouldReceive('find')->with(1)->once()->andReturn(array('id'=>1));
$this->call('GET', 'admin/posts/edit/1');
$this->assertViewHas('post', array('id'=>1));
}
}
के लिए परीक्षा है रनिंग PHPUnit मुझे त्रुटि देता है:
Fatal error: Using $this when not in object context in ...\www\l4\vendor\mockery\mockery\library\Mockery\Generator.php(130) : eval()'d code on line 73
यह स्पष्ट रूप से है क्योंकि find()
को स्थिर कार्य के रूप में घोषित किया गया है। अब, कोड त्रुटियों के बिना काम करता है, तो मैं असफल मॉडल के बिना सफलतापूर्वक नकल कैसे कर सकता हूं। चूंकि हम निर्भरता इंजेक्शन पर भरोसा कर रहे हैं, इसलिए मुझे find()
गैर-स्थैतिक रूप से कॉल करना होगा, अन्यथा मैं केवल Post::find()
कर सकता हूं।
एक समाधान है कि मैं के साथ आया था BaseModel
public function nsFind($id, $columns = array('*'))
{
return self::find($id, $columns);
}
में एक गैर स्थिर find()
प्रतिस्थापन बनाने के लिए है लेकिन जैसे-जैसे समारोह अलग नाम होना आवश्यक है यह एक बड़ा दर्द है!
क्या मैं कुछ गलत कर रहा हूं या आपके पास कोई बेहतर विचार है?
[यह प्रश्न] (http://stackoverflow.com/questions/19753502/mocking-static-eloquent-models-methods-cluding-find) - जवाब देने के साथ जेफररी वे का जवाब नीचे काम करता है – neyl