I am learning codeception and I wonder what is the difference between stubs and fixtures.
Both help me to load well-defined data and kepp tessts simple.
But when do I use
\Codeception\Util\Stub and when do I use
\Codeception\Util\Fixtures
So a stub is what Codeception uses to mock objects. In short, mocking is creating objects that simulate the behaviour of real objects.
Here is an example:
class UpdateBalance
{
public $balanceRepository;
public function __construct(BalanceRepositoryInterface $balanceRepository)
{
$this->balanceRepository = $balanceRepository;
}
public function subtract($amount, $id)
{
$updatedAmount = $this->balanceRepository->subtract($amount, $id);
if ($updatedAmount < 0) {
throw NegativeBalanceException($updatedAmount, $id);
}
return $updatedAmount;
}
}
class UpateBalanceTest extends PHPUnit_Framework_TestCase
{
public function testSubtractThrowsNegativeBalanceException()
{
$balanceRepository = Stub::make(
'BalanceRepositoryInterface'
array(
'subtract' => Stub::atLeastOnce(function() { return -100 })
)
);
$updateBalance = new UpdateBalance($balanceRepository);
$this->expectException(NegativeBalanceException::class);
$updateBalance->subtract(100, 1);
}
}
Note that we don't have a BalanceRepsository class. We have used Codeception stubs and pretended that the BalanceRepository class exists. By pretending it exists we can test the functionality of the UpdateBalance::subtract function by checking that the NegativeBalanceException is thrown.
Fixtures on the other hand would be for sharing test data throughout all your tests. If we use the UpdateBalance::subtract() example again, we could stress test the amount field ensuring it throws the correct exception depending on the amount being passed through:
// In some bootstrap or setup function
Fixtures::add('zero-amount', 0);
Fixtures::add('negative-amount', -1);
Fixtures::add('string-negative-amount', '-1');
class UpdateBalance
{
// ...
public function subtract($amount, $id)
{
if ($amount < 0) {
throw new
}
// ...
}
}
class UpateBalanceTest extends PHPUnit_Framework_TestCase
{
// ...
public function testSubtractThrowsCantSubtractNegativeAmountException()
{
$balanceRepository = Stub::make(
'BalanceRepositoryInterface'
);
$updateBalance = new UpdateBalance($balanceRepository);
$this->expectException(CantSubtractNegativeAmountException::class);
$updateBalance->subtract(Fixture::get('negative-amount'), 1);
}
}
Now we can use our pre-defined fixtures throughout all our tests. I would like to point out that using fixtures in the above example would probably be overkill, but for more complex test data like checking hexadecimal values are valid then it would be a lot more useful.
Related
public enum SystemConstants
{
SystemTypeDocument,
ApplicationTypeDocument
}
public interface ISystemBaseObject
{
SystemConstants SystemType();
}
public class ExploreMockExample
{
ISystemBaseObject systemBaseObject;
public ExploreMockExample(ISystemBaseObject systemObject)
{
systemBaseObject = systemObject;
}
public int MethodToBeTested()
{
if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument)
{
return 1;
}
else
{
return 2;
}
}
}
Using intellitest along with NUnit3.
When I right click MethodToBeTested, and then select run intellitest, expected outcome is Intellitest test should achieve maximum code coverage and create test case with valid test data to cover both if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument) and else branch statement.
Some blogs suggested to create factory for class and create mock object of interface. And use PexChoose static method to allow pex framework to explore code to achieve maximum code coverage.
[PexFactoryMethod(typeof(ExploreMockExample))]
public static ExploreMockExample CreateMock()
{
var mockComosBaseObject = new Mock<ISystemBaseObject>();
mockComosBaseObject.Setup(c =>c.SystemType()).
Returns(PexChoose.EnumValue<SystemConstants>(nameof(SystemConstants)));
return new ExploreMockExample(mockComosBaseObject.Object);
}
With above setup, Intellitest could above to generate only one test case which is covering if statement, if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument).
What can be done, to allow intellitest to create test case which will cover else statement having result value as 2.
Create mock implementation for your interface. Like mentioned below,
public class SystemBaseObject : ISystemBaseObject
{
public SystemConstants SystemType()
{
return PexChoose.EnumValue<SystemConstants>("SystemConstants");
}
}
PexChoose will help intellitest to explore code, return value will depend upon uses of SystemConstants in original class.
Then, create factory of ExploreMockExample using SystemBaseObject,
[PexFactoryMethod(typeof(ExploreMockExample))]
public static ExploreMockExample Create()
{
return new ExploreMockExample(new SystemBaseObject());
}
Run Intellitest on actual method MethodToBeTested, Intellitest will create 2 unit test case to cover both if else branch statement.
First test case,
[PexGeneratedBy(typeof(ExploreMockExampleTest))]
public void MethodToBeTested806()
{
ExploreMockExample exploreMockExample;
int i;
exploreMockExample = ExploreMockExampleFactory.Create();
i = this.MethodToBeTested(exploreMockExample);
PexAssert.AreEqual<int>(1, i);
PexAssert.IsNotNull((object)exploreMockExample);
}
Kindly observe PexAssert.AreEqual(1, i), which will cover if branch.
Second test case,
[PexGeneratedBy(typeof(ExploreMockExampleTest))]
public void MethodToBeTested792()
{
ExploreMockExample exploreMockExample;
int i;
exploreMockExample = ExploreMockExampleFactory.Create();
IPexChoiceRecorder choices = PexChoose.Replay.Setup();
choices.NextSegment(1).DefaultSession
.At(0, "SystemConstants", (object)(SystemConstants.ApplicationTypeDocument));
i = this.MethodToBeTested(exploreMockExample);
PexAssert.AreEqual<int>(2, i);
PexAssert.IsNotNull((object)exploreMockExample);
}
Kindly observe PexAssert.AreEqual(2, i), which will cover else branch.
Using PexChoose.Replay.Setup() it will return IPexChoiceRecorder, and it will make choice about to have SystemConstants.ApplicationTypeDocument as argument value to cover else block.
I am very new to TDD. I am using phpunit 7.4x-dev. I have the following abstract class that I am trying to develop unit tests for.
use PDO;
abstract class Model {
protected static function getDB() {
static $db = null;
if ($db === null) {
$db = new PDO(ConfigDatabase::DSN, ConfigDatabase::USER, ConfigDatabase::PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $db;
}
}
I have created the following test to get around the need to deal with the static protected method. And it works if I provide "ConfigureDatabase" class.
use PHPUnit\Framework\TestCase;
class ModelTest extends TestCase {
function newMockClass(){
$stub = new class() extends Model{
function getStaticMethod($methodName){
return self::$methodName();
}
};
return $stub;
}
public function testDatabaseExists() {
$stub = $this->newMockClass();
$db = $stub->getStaticMethod('getDB');
$this->assertInstanceOf(PDO::class,$db);
}
}
Since I do not want my tests to rely on any actual database, How would I fake the calls to PDO.
Following Dormilich suggestion I developed a database interface, just in case I decide later I do not want to use PDO.
interface CRUDImp {
function __construct($datbaseBridgeLikePDO);
...
}
Next I wrote my tests for the constructor. I used setup to make sure I was starting with a fresh mock of \PDO.
class PDOWrapperTest extends TestCase {
private $pdoMock;
private $db;
function setup() {
$this->pdoMock = $this->createMock('\PDO');
$this->db = new PDOWrapper($this->pdoMock);
}
public function testWrapperExists() {
$this->pdoMock->method('getAttribute')->willReturn(\PDO::ERRMODE_EXCEPTION);
$db = new PDOWrapper($this->pdoMock);
$x = $db instanceof CRUDImp;
$this->assertTrue($x);
}
/**
* #expectedException \Exception
*/
public function testNonPDOPassedToConstructor() {
$mock = $this->createMock('\Exception');
$x = new PDOWrapper($mock);
}
...
}
Since PHP is loosely typed I check to make sure that the class passed to the constructor was an instance of \PDO. I implemented the concrete class as follows
class PDOWrapper implements CRUDImp {
private $pdo;
private $dataOutputType = \PDO::FETCH_ASSOC;
public function __construct($pdo) {
if (!($pdo instanceof \PDO)) {
throw new \Exception("PDOWrapper must be passed instance of \PDO");
}
$attr_Errmode = $pdo->getAttribute(\PDO::ATTR_ERRMODE);
if ($attr_Errmode !== \PDO::ERRMODE_EXCEPTION) {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
$this->pdo = $pdo;
}
...
}
Now that I have an independent database wrapper the original Model tests are at the moment trivial and no longer needed. The abstract class Model was modified as follows:
abstract class Model {
protected $database=null;
function __construct(CRUDWrapper $database) {
$this->database = $database;
}
...
}
So for those not familiar with dependency injection I found the following links helpful:
http://php-di.org/doc/understanding-di.html
https://codeinphp.github.io/post/dependency-injection-in-php/
https://designpatternsphp.readthedocs.io/en/latest/Structural/DependencyInjection/README.html
Hope this shortens someone's work.
AspectMock is working fine, except for mocking of a constructor.
As an example, using a very simple class:
class SimpleClass
{
public $var1;
public function __construct($var1)
{
$this->var1 = $var1;
}
}
With a very simple test:
public function testConstructorMock()
{
$mockedClass = test::double('SimpleClass')->make();
$mockedClass->var1 = 2;
$mocked = test::double('SimpleClass',[
'__construct' => $mockedClass,
]);
$mySimpleClass = new SimpleClass(0);
print_r($mySimpleClass);
}
The returned object ($mySimpleClass) has a null value rather than the mocked value.
Everything else works fine, just the mocking of the constructor is problematic. Any ideas how to correct this?
Currently, I have a PHPUnit test case that extends PHPUnit_Extensions_SeleniumTestCase. Each function that starts requires a $this->setBrowserUrl() and defaults to starting a new Firefox browser window with each function call.
I want to have a test case that launches the browser for specific functions, but not launch the browser for other functions, as to save the resources and time it takes in opening and closing the browser. Is it possible for me to have such a file?
You best option is probably to create two separate test suites, one that uses uses Selenium commands and the other that does not use any Selenium functionality..
class BrowserTests extends PHPUnit_Extensions_SeleniumTestCase
{
protected function setUp()
{
$this->setBrowser('*firefox /usr/lib/firefox/firefox-bin');
...
}
public function testOne()
{
...
}
...
}
class NonBrowsterTests extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
...
}
public function testOne
{
...
}
...
}
Figured out a custom solution using PHPUnit annotations (and wrote a blog post about it!)
http://blog.behance.net/dev/custom-phpunit-annotations
EDIT: Adding some code here, as to make my answer more complete :)
In short, use custom annotations. In your setUp(), parse the doc block to grab annotations, and tag tests with different qualities. This would allow you to tag certain tests to run with a browser, and certain tests to run without.
protected function setUp() {
$class = get_class( $this );
$method = $this->getName();
$reflection = new ReflectionMethod( $class, $method );
$doc_block = $reflection->getDocComment();
// Use regex to parse the doc_block for a specific annotation
$browser = self::parseDocBlock( $doc_block, '#browser' );
if ( !self::isBrowser( $browser )
return false;
// Start Selenium with the specified browser
} // setup
private static function parseDocBlock( $doc_block, $tag ) {
$matches = array();
if ( empty( $doc_block ) )
return $matches;
$regex = "/{$tag} (.*)(\\r\\n|\\r|\\n)/U";
preg_match_all( $regex, $doc_block, $matches );
if ( empty( $matches[1] ) )
return array();
// Removed extra index
$matches = $matches[1];
// Trim the results, array item by array item
foreach ( $matches as $ix => $match )
$matches[ $ix ] = trim( $match );
return $matches;
} // parseDocBlock
I have the following code(simplified).
public class OrderProcessor
{
public virtual string PlaceOrder(string test)
{
OrderParser orderParser = new OrderParser();
string tester = orderParser.ParseOrder(test);
return tester + " here" ;
}
}
public class OrderParser
{
public virtual string ParseOrder(string test)
{
if (!string.IsNullOrEmpty(test.Trim()))
{
if (test == "Test1")
return "Test1";
else
{
return "Hello";
}
}
else
return null;
}
}
My test is as follows -
public class OrderTest
{
public void TestParser()
{
// Arrange
var client = MockRepository.GenerateMock<OrderProcessor>();
var spec = MockRepository.GenerateStub<OrderParser>();
spec.Stub(x => x.ParseOrder("test")).IgnoreArguments().Return("Test1");
//How to pass spec to client so that it uses the same.
}
}
Now how do I test client so that it uses the mocked method from OrderParser.
I can mock the OrderParser but how do I pass that to the orderProcessor mocked class?
Please do let me know.
Thanks in advance.
I'm a little confused by your test since you are not really testing anything except that RhinoMocks works. You create two mocks and then do some assertions on them. You haven't even tested your real classes.
You need to do some dependency injection if you really want to get a good unit test. You can quickly refactor your code to use interfaces and dependency injection to make your test valid.
Start by extracting an interface from your OrderParser class:
public interface IOrderParser
{
String ParseOrder(String value);
}
Now make sure your OrderParser class implements that interface:
public class OrderParser: IOrderParser{ ... }
You can now refactor your OrderProcessor class to take in an instance of an IOrderParser object through its constructor. In this way you "inject" the dependency into the class.
public class OrderProcessor
{
IOrderParser _orderParser;
public OrderProcessor(IOrderParser orderParser)
{
_orderParser = orderParser;
}
public virtual string PlaceOrder(string val)
{
string tester = _orderParser.ParseOrder(val);
return tester + " here" ;
}
}
In your test you only want to mock out the dependency and not the SUT (Subject Under Test). Your test would look something like this:
public class OrderTest
{
public void TestParser()
{
// Arrange
var spec = MockRepository.GenerateMock<IOrderParser>();
var client = new OrderProcessor(spec);
spec.Stub(x => x.ParseOrder("test")).IgnoreArguments().Return("Test1");
//Act
var s = client.PlaceOrder("Blah");
//Assert
Assert.AreEqual("Test1 Here", s);
}
}
It is difficult for me to gauge what you are trying to do with your classes, but you should be able to get the idea from this. A few axioms to follow:
Use interfaces and composition over inheritance
Use dependency injection for external dependencies (inversion of control)
Test a single unit, and mock its dependencies
Only mock one level of dependencies. If you are testing class X which depends on Y which depends on Z, you should only be mocking Y and never Z.
Always test behavior and never implementation details
You seem to be on the right track, but need a little guidance. I would suggest reading material that Martin Fowler, and Bob Martin have to get up to speed.