Mock-object and dummy- (stub function) use in testing

Lecture



Mock-object (from the English. Mock object , literally: "object-parody", "object-imitation", as well as "stand") - in object-oriented programming - the type of objects that implement the specified aspects of the simulated software environment. for example internet connection emulation or work with databases

A mock object is a concrete fictitious implementation of an interface intended solely for testing the interaction and for which a statement is expressed.

In procedural programming, a similar construction is called “dummy” (English is a stub). A function that yields a constant, or a random variable from a valid range of values.

Mock-objects are actively used in the development through testing.

During the use of Bocs, Dependency injection is often used.

PHP Laravel example

<? php

class QuestionsControllerTest extends TestCase {

protected $ questionMock;

public function setUp ()
{
// $ this-> questionMock = Mockery :: mock ('Question');

$ this-> questionMock = Mockery :: mock (Question :: class);

$ this-> app-> instance (Question :: class, $ this-> questionMock);
}

public function testQuestionIndex ()
{
$ this-> questionMock
-> shouldReceive ('latest')
-> once ();

$ this-> app-> instance ('Question', $ this-> questionMock);

$ this-> call ('GET', 'questions');
}

<? php namespace App \ Http \ Controllers;

use App \ Http \ Requests \ QuestionRequest;
use App \ Http \ Controllers \ Controller;

use App \ Question;

use Auth;
use Request;

class QuestionsController extends Controller {

protected $ question;

public function __construct (Question $ question)
{
$ this-> question = $ question;
}

public function index ()
{
$ questions = $ this-> question-> latest () -> get ();

return view ('questions.index', compact ('questions'));
}
...

launch

$ ./vendor/bin/phpunit tests / controllers / QuestionsControllerTest.php PHPUnit 4.5.0 by Sebastian Bergmann and contributors.

Time: 135 ms, Memory: 12.50Mb

A stub function (in programming) is a function that performs no meaningful action and returns an empty result or input data as it is. Same as the stub method.

Used by:

  • For clarity, when designing the structure of application classes.
  • Some functions may be “muted” for debugging other functions.
  • To restrict access to certain fields of the class (for example, to the root of a tree).

An example of a stub function in the C language:

void stub ()
{
return ;
}

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Quality Assurance"

Terms: Quality Assurance