phpunit abstract class constant - class

I'm trying to find a way to test a abstract class constant that must exist and match/not match a value. Example:
// to be extended by ExternalSDKClild
abstract class ExternalSDK {
const VERSION = '3.1.1.';
}
class foo extends AController {
public function init() {
if ( ExternalSDK::VERSION !== '3.1.1' ) {
throw new Exception('Wrong ExternalSDK version!');
}
$this->setExternalSDKChild(new ExternalSDKChild());
}
}
Limitations... The framework we use doesn't allow dependency injection in the init() method. (Suggestion to refactor the init() method could be the way to go...)
The unit tests and code coverage I have run, cover all but the Exception. I can't figure out a way to make the ExternalSDK::Version to be different from what it is.
All thoughts welcome

First, refactor the call to new into a separate method.
Second, add a method to acquire the version instead of accessing the constant directly. Class constants in PHP are compiled into the file when parsed and cannot be changed.* Since they are accessed statically, there's no way to override it without swapping in a different class declaration with the same name. The only way to do that using standard PHP is to run the test in a separate process which is very expensive.
class ExternalSDK {
const VERSION = '3.1.1';
public function getVersion() {
return static::VERSION;
}
}
class foo extends AController {
public function init() {
$sdk = $this->createSDK();
if ( $sdk->getVersion() !== '3.1.1' ) {
throw new Exception('Wrong ExternalSDK version!');
}
$this->setExternalSDKChild($sdk);
}
public function createSDK() {
return new ExternalSDKChild();
}
}
And now for the unit test.
class NewerSDK extends ExternalSDK {
const VERSION = '3.1.2';
}
/**
* #expectedException Exception
*/
function testInitFailsWhenVersionIsDifferent() {
$sdk = new NewerSDK();
$foo = $this->getMock('foo', array('createSDK'));
$foo->expects($this->once())
->method('createSDK')
->will($this->returnValue($sdk));
$foo->init();
}
*Runkit provides runkit_constant_redefine() which may work here. You'll need to catch the exception manually instead of using #expectedException so you can reset the constant back to the correct value. Or you can do it in tearDown().
function testInitFailsWhenVersionIsDifferent() {
try {
runkit_constant_redefine('ExternalSDK::VERSION', '3.1.0');
$foo = new foo();
$foo->init();
$failed = true;
}
catch (Exception $e) {
$failed = false;
}
runkit_constant_redefine('ExternalSDK::VERSION', '3.1.1');
if ($failed) {
self::fail('Failed to detect incorrect SDK version.');
}
}

Related

How to override a Dart method on instantiation? [duplicate]

Is there way to overriding method in Dart like JAVA, for example:
public class A {
public void handleLoad() {
}
}
And when overriding:
A a = new A() {
#Override
public void handleLoad() {
// do some code
}
};
No, Dart does not have anonymous classes. You have to create a class that extends A and instantiate it.
No but it much less useful in Dart because you can just reassign function:
typedef void PrintMsg(msg);
class Printer {
PrintMsg foo = (m) => print(m);
}
main() {
Printer p = new Printer()
..foo('Hello') // Hello
..foo = ((String msg) => print(msg.toUpperCase()))
..foo('Hello'); //HELLO
}
However you will need some extra boilerplate to access instance.
Use type Function:
class A {
final Function h
A(this.h);
void handleLoad(String loadResult) { h(loadResult); }
}
Or
class A {
final Function handleLoad;
A(this.handleLoad);
}
A a = new A((String loadResult){
//do smth.
});

How to set type definitions depending on the extending class in dartlang

Is there a way to declare return types of methods or the object-prefix to be the "extendingClass" like you would do in PHP with the static::class?
So for example:
abstract class AbstractModel {
// Should return the database-provider for the given model
dynamic get modelProvider;
// Save instance to Database - Create new if no ID exists,
// else update existing
dynamic save() {
if( id == null ) {
modelProvider.insert(this);
} else {
modelProvider.update(this);
}
return this;
}
}
class ToDo extends AbstractModel {
ToDoProvider get modelProvider {
return ToDoProvider;
}
}
So in this example, obviously AbstractModel does not yet know what the return type of modelProvider will be, but I do know that it will always be the same type for a given child. Also, the return type of the save method would always be the child-class. But when writing it like this I will get an error for overwriting the modelProvider with an invalid return type.
Due to darts javascript-like nature I assume there is no way to actually achieve this like you would in PHP. But then I wonder how to type-save build re-usable code? I am trying to implement a small eloquent like query-scheme for my models so I don't have to write each CRUD method for every model - but I would still like to be precise about the types and not use dynamic everywhere.
So is there a way to do that in dart or am I completely off the track regarding dart standards?
You can use generics:
abstract class AbstractModel<ChildType extends AbstractModel<ChildType>> {
// Should return the database-provider for the given model
ModelProvider<ChildType> get modelProvider;
// Save instance to Database - Create new if no ID exists,
// else update existing
ChildType save() {
if( id == null ) {
modelProvider.insert(this);
} else {
modelProvider.update(this);
}
return this;
}
}
class Model extends AbstractModel<Model> {
}
abstract class ModelProvider<T> {
void insert(T value);
void update(T value);
}
class MyModelProvider extends ModelProvider<Model> {
...
}

How to access Model in Controller in zend framework?

I am trying to call model methods from controller. but I am getting Fatal error: Class 'GuestModel' not found in. error
following is the code ::
Controller ::
class GuestController extends Zend_Controller_Action
{
public function indexAction(){
$guestbook = new GuestModel();
$this->view->entries = $guestbook->fetchAll();
}
}
Model::
class GuestModel extends Zend_Db_Table_Abstract
{
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Guestbook();
$entry->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
$entries[] = $entry;
}
return $entries;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Guestbook');
}
return $this->_dbTable;
}
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
}
Zend Framework autoload depends on using the correct directory structure and file naming conventions to find the classes automagically, from the looks of your code my guess would be you're not following it.
I see 2 possible solutions for your problem:
If possible, rename your class to Application_Model_Guestbook, the file to Guestbook.php and make sure to move it to your application/models/ directory. Then you just need to call it in your controller as $guestbook = new Application_Model_Guestbook();. Check this documentation example;
Create your own additional autoloading rules. Check the official documentation regarding Resource Autoloading.

need to test functionality with oracle stored proc

i have code like this:
protected function _checkUserVisibility()
{
try {
if (!$params->getUsrParametr(self::ACTIVE_FIF)) { // calling oracle stored proc
throw new Unitex_Exception('ALARM');
}
}
catch (Exception $e) {
$this->logOut();
throw $e;
}
}
this func caled from another one (and so on).
a a question:
how to get worked unit test for that parts of code?
EDIT1:
firstly taked hehe http://framework.zend.com/manual/1.12/en/zend.test.phpunit.html
than improoved (hope)
test proc is:
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase {
..........
public function testLoginAction()
{
$request = $this->getRequest();
$request->setMethod('POST')
->setHeader('X_REQUESTED_WITH', 'XMLHttpRequest')
->setPost(array(
'user' => 'test_user',
'password' => 'test_pwd',
));
$filialId = 1;
$stmt1 = Zend_Test_DbStatement::createUpdateStatement();
$this->getAdapter()->appendStatementToStack($stmt1);
$this->getAdapter()->appendStatementToStack($stmt1);
$this->getAdapter()->appendStatementToStack($stmt1);
$this->getAdapter()->appendStatementToStack($stmt1);
$stmt1Rows = array(array('IRL_ALIAS' => 'RO_COMMON', 'ISADM' => 'N'));
$stmt1 = Zend_Test_DbStatement::createSelectStatement($stmt1Rows);
$this->getAdapter()->appendStatementToStack($stmt1);
$this->dispatch('/user/login');// <-- crash here
$this->assertController('user');
$this->assertAction('login');
$this->assertNotRedirect();
$this->_getResponseJson();
}
In your unit test definitly you don't want any database interaction. The answer for your question is use stub for db functionality.
Let say that $params is property of SomeClass contains getUsrParametr which for example gets something from database. You're testing _checkUserVisibility method so you don't care about what are happening in SomeClass. That's way you test will look something like that:
class YourClass
{
protected $params;
public function __construct(SomeClass $params)
{
$this->params = $params;
}
public function doSomething()
{
$this->_checkUserVisibility();
}
protected function _checkUserVisibility()
{
try {
if (!$this->params->getUsrParametr(self::ACTIVE_FIF)) { // calling oracle stored proc
throw new Unitex_Exception('ALARM');
}
}
catch (Exception $e) {
$this->logOut();
throw $e;
}
}
}
And the unit test of course the only method you test is the public one, but you cover protected method through testing public one.
public function testDoSomethingAlarm()
{
// set expected exception:
$this->setExpectedException('Unitex_Exception', 'ALARM');
// create the stub
$params = $this->getMock('SomeClass', array('getUsrParametr'));
// and set desired result
$params->expects($this->any())
->method('getUsrParametr')
->will($this->returnValue(false));
$yourClass = new YourClass($params);
$yourClass->doSomething();
}
And the second test which test case if getUsrParametr will returns true:
public function testDoSomethingLogout()
{
// set expected exception:
$this->setExpectedException('SomeOtherException');
// create the stub
$params = $this->getMock('SomeClass', array('getUsrParametr'));
// set throw desired exception to test logout
$params->expects($this->any())
->method('getUsrParametr')
->will($this->throwException('SomeOtherException'));
// now you want create mock instead of real object beacuse you want check if your class will call logout method:
$yourClass = $this->getMockBuilder('YourClass')
->setMethods(array('logOut'))
->setConstructorArgs(array($params))
->getMock();
// now you want ensure that logOut will be called
$yourClass->expects($this->once())
->method('logOut');
// pay attention that you've mocked only logOut method, so doSomething is real one
$yourClass->doSomething();
}
If you're using PHP 5.3.2+ with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests, otherwise you test protected/private methods by properly testing the public methods that use the protected/private methods. Generally speaking the later of the two options is generally how you should do it, but if you want to use reflection, here's a generic example:
protected static function getMethod($name) {
$class = new ReflectionClass('MyClass');
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
public function testFoo() {
$foo = self::getMethod('foo');
$obj = new MyClass();
$foo->invokeArgs($obj, array(...));
...
}

How do I mock Class<? extends List> myVar in Mockito?

I want to mock a Class in Mockito. It will then have a .newInstance() call issued which will be expected to return an actual class instance (and will return a mock in my case).
If it was setup correctly then I could do:
ArrayList myListMock = mock(ArrayList.class);
when(myVar.newInstance()).thenReturn(myListMock);
I know I can set it up so that a new instance of class ArrayList will be a mock (using PowerMockito whenNew), just wondering if there was a way to mock this kind of a class object so I don't have to override instance creation...
Below is the real class I'm trying to mock, I can't change the structure it is defined by the interface. What I'm looking for is a way to provide cvs when initialize is called.
public class InputConstraintValidator
implements ConstraintValidator<InputValidation, StringWrapper> {
Class<? extends SafeString> cvs;
public void initialize(InputValidation constraintAnnotation) {
cvs = constraintAnnotation.inputValidator();
}
public boolean isValid(StringWrapper value,
ConstraintValidatorContext context) {
SafeString instance;
try {
instance = cvs.newInstance();
} catch (InstantiationException e) {
return false;
} catch (IllegalAccessException e) {
return false;
}
}
Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There's no good way to use Mockito to replace a function on the Class object itself. This leaves you with a few options:
I don't have experience with PowerMock but it seems it's designed for mocking static methods.
In dependency-injection style, make your static factory method into a factory instance. Since it looks like you're not actually working with ArrayList, let's say your class is FooBar instead:
class FooBar {
static class Factory {
static FooBar instance;
FooBar getInstance() {
if (instance == null) {
instance = new FooBar();
}
return instance;
}
}
// ...
}
Now your class user can receive a new FooBar.Factory() parameter, which creates your real FooBar in singleton style (hopefully better and more threadsafe than my simple implementation), and you can use pure Mockito to mock the Factory. If this looks like it's a lot of boilerplate, it's because it is, but if you are thinking of switching to a DI solution like Guice you can cut down a lot of it.
Consider making a field or method package-private or protected and documenting that it's visible for testing purposes. Then you can insert a mocked instance in test code only.
public class InputConstraintValidator implements
ConstraintValidator<InputValidation, StringWrapper> {
Class<? extends SafeString> cvs;
public void initialize(InputValidation constraintAnnotation) {
cvs = constraintAnnotation.inputValidator();
}
public boolean isValid(StringWrapper value,
ConstraintValidatorContext context) {
SafeString instance;
try {
instance = getCvsInstance();
} catch (InstantiationException e) {
return false;
} catch (IllegalAccessException e) {
return false;
}
}
#VisibleForTesting protected getCvsInstance()
throws InstantiationException, IllegalAccessException {
return cvs.newInstance();
}
}
public class InputConstaintValidatorTest {
#Test public void testWithMockCvs() {
final SafeString cvs = mock(SafeString.class);
InputConstraintValidator validator = new InputConstraintValidator() {
#Override protected getCvsInstance() {
return cvs;
}
}
// test
}
}
I think you just need to introduce an additional mock for Class:
ArrayList<?> myListMock = mock(ArrayList.class);
Class<ArrayList> clazz = mock(Class.class);
when(clazz.newInstance()).thenReturn(myListMock);
Of course the trick is making sure your mocked clazz.newInstance() doesn't end up getting called all over the place because due to type-erasure you can't specify that it's actually a Class<ArrayList>.
Also, be careful defining your own mock for something as fundamental as ArrayList - generally I'd use a "real one" and populate it with mocks.