silverstripe-framework/tests/forms/MoneyFieldTest.php

100 lines
2.4 KiB
PHP
Raw Normal View History

<?php
/**
* @package framework
* @subpackage tests
*/
class MoneyFieldTest extends SapphireTest {
2014-08-15 08:53:05 +02:00
protected $extraDataObjects = array(
'MoneyFieldTest_Object',
'MoneyFieldTest_CustomSetter_Object',
);
public function testSaveInto() {
$o = new MoneyFieldTest_Object();
2014-08-15 08:53:05 +02:00
$m = new Money();
$m->setAmount(123456.78);
$m->setCurrency('EUR');
$f = new MoneyField('MyMoney', 'MyMoney', $m);
2014-08-15 08:53:05 +02:00
$f->saveInto($o);
$this->assertEquals(123456.78, $o->MyMoney->getAmount());
$this->assertEquals('EUR', $o->MyMoney->getCurrency());
}
2014-08-15 08:53:05 +02:00
public function testSetValueAsMoney() {
$o = new MoneyFieldTest_Object();
2014-08-15 08:53:05 +02:00
$f = new MoneyField('MyMoney', 'MyMoney');
2014-08-15 08:53:05 +02:00
$m = new Money();
$m->setAmount(123456.78);
$m->setCurrency('EUR');
$f->setValue($m);
2014-08-15 08:53:05 +02:00
$f->saveInto($o);
$this->assertEquals(123456.78, $o->MyMoney->getAmount());
$this->assertEquals('EUR', $o->MyMoney->getCurrency());
}
2014-08-15 08:53:05 +02:00
public function testSetValueAsArray() {
$o = new MoneyFieldTest_Object();
2014-08-15 08:53:05 +02:00
$f = new MoneyField('MyMoney', 'MyMoney');
2014-08-15 08:53:05 +02:00
$f->setValue(array('Currency'=>'EUR','Amount'=>123456.78));
2014-08-15 08:53:05 +02:00
$f->saveInto($o);
$this->assertEquals(123456.78, $o->MyMoney->getAmount());
$this->assertEquals('EUR', $o->MyMoney->getCurrency());
}
/**
* This UT tests if saveInto used customised getters/setters correctly.
* Saving values for CustomMoney shall go through the setCustomMoney_Test
2014-08-15 08:53:05 +02:00
* setter method and double the value.
*/
public function testSetValueViaSetter() {
$o = new MoneyFieldTest_CustomSetter_Object();
2014-08-15 08:53:05 +02:00
$f = new MoneyField('CustomMoney', 'Test Money Field');
$f->setValue(array('Currency'=>'EUR','Amount'=>123456.78));
2014-08-15 08:53:05 +02:00
$f->saveInto($o);
$this->assertEquals((2 * 123456.78), $o->MyMoney->getAmount());
$this->assertEquals('EUR', $o->MyMoney->getCurrency());
}
}
class MoneyFieldTest_Object extends DataObject implements TestOnly {
private static $db = array(
2014-08-15 08:53:05 +02:00
'MyMoney' => 'Money',
);
}
/**
* Customised class, implementing custom getter and setter methods for
* MyMoney.
*/
class MoneyFieldTest_CustomSetter_Object extends DataObject implements TestOnly {
private static $db = array(
2014-08-15 08:53:05 +02:00
'MyMoney' => 'Money',
);
2014-08-15 08:53:05 +02:00
public function getCustomMoney() {
return $this->MyMoney->getValue();
}
2014-08-15 08:53:05 +02:00
public function setCustomMoney($value) {
2014-08-15 08:53:05 +02:00
$newAmount = $value->getAmount() * 2;
$this->MyMoney->setAmount($newAmount);
$newAmount = $value->getAmount() * 2;
$this->MyMoney->setCurrency($value->getCurrency());
}
}