Eloquent class not found when testing new models - phpunit

I'm trying to test my eloquent models but my tests keep failing with "Class 'Eloquent' not found" errors. If I add a route that uses my eloquent model and simply prints some of the information stored in the database, everything works fine. It is only when trying to run phpunit that I get the issues with eloquent not being found. My model is in app/models so it should be included in the composer classmap and I've done composer dump-autoload. I'm sure I'm overlooking something really obvious but I can't pick it out. Any idea what the issue is?
My test:
class GameTest extends TestCase {
public function setUp(){
$this->game = Game::find(1);
}
public function testGameInstance(){
$this->assertInstanceOf('Game', $this->game);
}
}
My model:
class Game extends Eloquent{
protected $table = 'gm_game';
protected $primaryKey = 'game_id';
}

Try adding parent::setUp() in your test's setUp function. This solved the issue for me.
Example:
class GameTest extends TestCase {
public function setUp(){
parent::SetUp();
$this->game = Game::find(1);
}
public function testGameInstance(){
$this->assertInstanceOf('Game', $this->game);
}
}

Related

PowerMockito mockStatic gives MissingMethodInvocationException

I am trying to mockStatic method using PowerMockito , where I tried some options to mockStatic for a class, resulting in different exceptions.
#RunWith(PowerMockRunner.class)
#PrepareForTest({Base64.class})
public class BqClientFactoryTest {
#Test
public void testGetBigQueryClient() throws Exception {
mockStatic(Base64.class);
Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
when(Base64.getDecoder()).thenReturn(mockDecoder);
This resulted in org.mockito.exceptions.misusing.MissingMethodInvocationException:
I used another example like this
#RunWith(PowerMockRunner.class)
#PrepareForTest({Base64.class})
public class BqClientFactoryTest {
#Test
public void testGetBigQueryClient() throws Exception {
mockStatic(Base64.class);
Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
doReturn(mockDecoder).when(Base64.class, "getDecoder");
which gives me
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
If I use
BDDMockito.given(Base64.getDecoder()).willReturn(mockDecoder);
from Mocking static methods with Mockito , it still returns org.mockito.exceptions.misusing.MissingMethodInvocationException
I tried to check similar questions on SO, they haven't seemed to help.
Any help resolving this is appreciated.
I solved it following this, all other solutions didn't work for me. It is difficult to search for this solution, since there are too many on SO on the same.
PowerMockito mock single static method and return object inside another static method , PowerMock, mock a static method, THEN call real methods on all other statics
#RunWith(PowerMockRunner.class)
#PrepareForTest({Base64.class})
public class BqClientFactoryTest {
#Test
public void testGetBigQueryClient() throws Exception {
Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
stub(method(Base64.class, "getDecoder")).toReturn(mockDecoder);

In phpunit what is the difference between __construct versus setup?

I am curious to know it is good practice to create object in test class __construct or we should always use setup/teardown approach ( or setUpBeforeClass/tearDownAfterClass approach)?
I aware of the fact set/teardown gets called for each test so will it do any good if I put my object creation code in it? e.g.
//mytestclass.php
class MyTestClass extends PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new FooClass();
}
public testFooObj()
{
//assertions for $this->obj
}
...
}
what could be the issues if I create object in constructor like this:
class MyTestClass extends PHPUnit_Framework_TestCase
{
private $obj;
protected function __construct()
{
$this->obj = new FooClass();
}
public testFooObj()
{
//assertions for $this->obj
}
...
}
I tried googling around as well as PHPUnit documentation couldn't get much information about, Can you please help me to understand which one is good practice?
setUp() gets called before each of your tests is ran. __construct() happens when your class is instantiated. So if you have multiple tests and they use local properties and modify them, using setUp() you can ensure that they are the same before each test is ran. The opposite of setUp() is tearDown() where you can ensure that test data gets cleaned up after each test.
As I have just found out, implementing the default class constructor instead of the setupBeforeClass() method breaks the #dataProvider annotations (probably all kinds of annotations), yielding a "Missing argument" exception for any parameterized tests.
Missing argument 1 for AppBundle\Tests\Service\InvitationVerifierTest::testDireccionInvalida()
Replacing public function __construct() for public static function setUpBeforeClass() gets rid of the exception. So there it goes, favor the setupBeforeClass() method over the regular constructor.
PHPUnit version 4.5.0

Handling specimen creation inconsistencies between AutoFixture and Moq

I am using AutoMoqCustomization in my test conventions.
Consider the code below. Everything works great until I add a constructor to one of the concrete classes. When I do, I get "could not find a parameterless constructor". We know AutoFixture doesn't have an issue with the constructor because it delivered me the test object one which proved to be assignable from IThings... no failure there. So it must be moq.
This makes some sense because I assume builder was generated by moq and passed into the GetCommands method. So I think I can see that control has been passed from AutoFixture to moq at that point.
That takes care of the why, but what should I do about it? Is there a way to instruct moq on how to deal with the ThingOne or is there a way to instruct AutoFixture to ignore moq for IThingBuilders and instead do something Fixtury?
public class TestClass
{
public interface IThingBuilders
{
T1 Build<T1>() where T1 : IThings;
}
public interface IThings
{
}
public class ThingOne : IThings
{
public ThingOne(string someparam)
{
}
}
public class ThingTwo : IThings
{
}
public class SomeClass
{
public List<IThings> GetCommands(IThingBuilders builder)
{
var newlist = new List<IThings>();
newlist.Add(builder.Build<ThingOne>());
newlist.Add(builder.Build<ThingTwo>());
return newlist;
}
}
[Theory, BasicConventions]
public void WhyCannotInstantiateProxyOfClass(ThingOne one, ThingTwo two, IThingBuilders builder, SomeClass sut)
{
Assert.IsAssignableFrom<IThings>(one);
Assert.IsAssignableFrom<IThings>(two);
var actual = sut.GetCommands(builder);
Assert.Equal(1, actual.OfType<ThingOne>().Count());
Assert.Equal(1, actual.OfType<ThingTwo>().Count());
}
}
As there's no extensibility point in Moq that enables AutoFixture to hook in and supply a value of ThingOne, there's not a whole lot you can do.
However, you can use the SetReturnsDefault<T> method of Moq. Modifying the above test would then be like this:
[Theory, BasicConventions]
public void WhyCannotInstantiateProxyOfClass(
ThingOne one, ThingTwo two, IThingBuilders builder, SomeClass sut)
{
Assert.IsAssignableFrom<IThings>(one);
Assert.IsAssignableFrom<IThings>(two);
Mock.Get(builder).SetReturnsDefault(one); // Add this to make the test pass
var actual = sut.GetCommands(builder);
Assert.Equal(1, actual.OfType<ThingOne>().Count());
Assert.Equal(1, actual.OfType<ThingTwo>().Count());
}
This is a bit easier than having to write a specific Setup/Returns pair, but not much. You could move that code to an AutoFixture Customization, but again, since this is a generic method on a a Mock instance, you'll explicitly need to call this for e.g. ThingOne in order to set the default for that return type. Not particularly flexible.

How to include Facebook-SDK

I'm using an example of FOSUserBundle with FOSFacebookBundle. Hereon i have build my application.
The relevant Project Structure is like following:
src\ABC\MainBundle\
src\ABC\UserBundle\
src\ABC\MainBundle\Controller\DefaultController.php
src\ABC\UserBundle\Security\User\Provider\FacebookProvider.php
vendor\facebook\php-sdk\src\base_facebook.php
Part of the FacebookProvider:
use \BaseFacebook;
use \FacebookApiException;
class FacebookProvider implements UserProviderInterface
{
protected $facebook;
public function __construct(BaseFacebook $facebook, $userManager, $validator)
{
$this->facebook = $facebook;
}
public function loadUserByUsername($username)
{
try {
$fbdata = $this->facebook->api('/me');
...
As you can see there is the Facebook-Object already available.
What i want to do now is nearly the same, but in my DefaultController:
use \BaseFacebook;
use \FacebookApiException;
class DefaultController extends BaseController
{
public function indexAction(){
$facebook = new Facebook('key', 'secret');
$fbfriends_obj = $facebook->api('/'.$fbid.'/friends');
...
But there i get the message
Fatal error: Class 'ABC\MainBundle\Controller\Facebook' not found in C:\xampp\htdocs\...\src\ABC\MainBundle\Controller\DefaultController.php on line x
Why is that? How can i access the facebook-class from inside my defaultcontroller? If its already possible for the facebookprovider, why it aint possible for my controller?
any hints will be really appreciated!
The solution to that problem is, that the facebook-class has no namespace and you have to do something like
$facebook = new \Facebook(...)
Problem is here:
use \BaseFacebook;
use \FacebookApiException;
You are importing BaseFacebook class from namespace you should use \Facebook (in Controller and FacebookProvider classes)

PHPUnit::How can be __construct with protected variables tested?

PhpUnit::How can be __construct with protected variables tested?
(not always we should add public method getVal()- soo without add method that return protected variable value)
Example:
class Example{
protected $_val=null;
function __construct($val){
$this->_val=md5 ($val);
}
}
Edit:
also exist problem to test in function that return void
Edit2:
Example why we need test __construct:
class Example{
protected $_val=null;
//user write _constract instead __construct
function _constract($val){
$this->_val=md5 ($val);
}
function getLen($value){
return strlen($value);
}
}
class ExampleTest extends PHPUnit_Framework_TestCase{
test_getLen(){
$ob=new Example();//call to __construct and not to _constract
$this->assertEquals( $ob->getLen('1234'), 4);
}
}
test run ok, but Example class "constructor" wasn't created!
Thanks
The main goal of unit testing is to test interface By default, you should test only public methods and their behaviour. If it's ok, then your class is OK for external using. But sometimes you need to test protected/private members - then you can use Reflection and setAccessible() method
Create a derived class that exposes the value that you want to test.

Resources