I keep getting the following error when trying to run a login script I have. I have created an Entities folder based on my already in place db schema.
Fatal error: Class 'User' not found in /xxxx/xxxxx/public_html/application/controllers/signup.php on line 23
Code:
public function __construct() {
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}
public function index() {
$this->load->view('login_form');
}
public function submit() {
if ($this->_submit_validate() === FALSE) {
$this->index();
return;
}
redirect('/');
}
private function _submit_validate() {
$this->form_validation->set_rules('UserName', 'Username',
'trim|required|callback_authenticate');
$this->form_validation->set_rules('Password', 'Password',
'trim|required');
$this->form_validation->set_message('authenticate','Invalid login. Please try again.');
return $this->form_validation->run();
}
public function authenticate() {
return Current_User::login($this->input->post('UserName'),
$this->input->post('Password'));
}
}
You haven't provide any information abount current_user class. I assume that current_user is your model in that case change the authenticate function to
public function authenticate() {
$this->load->model('current_user');
return $this->current_user->login($this->input->post('UserName'),
$this->input->post('Password'));
}
Related
I have a method as follows -
// A.ts
export abstract class A{
protected abstract method();
}
//B.ts
export class B extends A{
private _httpServer?: http.Server;
private _wsServer?: WebSocketServer;
constructor(){ super(); }
protected async method(){
init();
//some more method calls
}
private async init(){
this._httpServer = http.createServer(async (request, response) => {
if(something){
response.writeHead(statusCode, { 'Content-Type': 'text/plain' });
response.end();
}
else{
response.end("success")
}
})
this._httpServer.on('error', error => console.log(error));
this._httpServer.listen(8080);
this._wsServer = new WebSocketServer({ noServer: true, path: '/ws' });
}
}
I want to write tests for init() method. For that I want dummy request to sent so that I can enter inside createServer method and spy on inside codes to increase coverage. How can I do that?
Having some issues getting my repository to retrieve information - keeps coming back null. Any Thoughts would be appreciated - new to this and teaching myself.
Repository:
public class CustomerRepository : ICustomerRepository
{
private masterContext context;
public CustomerRepository(masterContext context)
{
this.context = context;
}
public IEnumerable<Customer> GetCustomers()
{
return context.Customer.ToList();
}
public Customer GetCustomerById(int customerId)
{
var result = (from c in context.Customer where c.CustomerId == customerId select c).FirstOrDefault();
return result;
}
public void Save()
{
context.SaveChanges();
}
Controller:
public class CustomerController : Controller
{
private readonly ICustomerRepository _repository = null;
public ActionResult Index()
{
var model = (List<Customer>)_repository.GetCustomers();
return View(model);
}
public ActionResult New()
{
return View();
}
}
MasterContext which i had efc make:
public partial class masterContext : DbContext
{
public masterContext(DbContextOptions<masterContext> options)
: base(options)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(entity =>
{
entity.Property(e => e.CustomerName).IsRequired();
});
}
public virtual DbSet<Customer> Customer { get; set; }
public virtual DbSet<Order> Order { get; set; }
}
I think you need to create instances of you Context and your Repository. So in your Controller you need to something like this:
private masterContext context = new masterContext();
private ICustomerRepository repository = new CustomerRepository(context);
I assume that you're not using Dependency injection ... if so you just need to create a Constructor for your Controller that takes CustomerRepository as argument:
public CustomerController(ICustomerRepository _repository) {
repository = _repository;
}
If you did not configure your database context, look here: https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html
This will than enable you the dependency injection. Everything you than need to do for the Repository is to use
services.AddScoped<ICustomerRepository,
CustomerRepository>();
And I think it could be good to remove the ToList() in the Repository class and remove the Cast List<Customer> in your Controller and use ToList() instead, if it's really needed. Because if you're using it in the View the ienumerable could also work.
In Laravel 5.2, I want to unit test my Eloquent User Repository.
class EloquentUserRepository implements UserRepositoryInterface
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function oneUser($id)
{
return $this->user->oneUser($id);
}
}
My test looks like below, with mocking the interface:
class EloquentUserRepositoryTest extends TestCase
{
public function setUp()
{
$this->user = factory(User::class, 1)->create(['name' => 'foo']);
}
/** #test */
public function it_fetch_an_user()
{
$mock = Mockery::mock('App\Repositories\Interfaces\UserRepositoryInterface')
->shouldReceive('oneUser')
->once()
->with($this->user->id)
->andReturn('foo');
App::instance(App\Repositories\EloquentUserRepository::class, $mock);
$userRepository = App::make(App\Repositories\EloquentUserRepository::class);
$this->assertEquals('foo', $userRepository->oneUser($this->user->id)->name);
}
public function tearDown()
{
Mockery::close();
}
}
I get this error:
ErrorException: call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'oneUser'
I expect a simulated object that has the method oneUser, but it returns Mockery\Expectation. What do I wrong?
When a new instance of EloquentUserRepository is made, a new user model is created. When you then call the oneUser method for the EloquentUserRepository class a method with the same name is called but on the user model. Therefore it's the user model you need to mock, not the UserRepositoryInterface.
You need to create a new instance of the EloquentUserRepository and send in the user model mock as an argument when it's created as shown below:
class EloquentUserRepositoryTest extends TestCase
{
protected $userMock;
public function setUp()
{
parent::setUp();
$this->userMock = Mockery::mock('User');
$this->userMock->id = 1;
}
/** #test */
public function it_fetch_an_user()
{
$this->userMock->shouldReceive('oneUser')->with($this->userMock->id)->andReturn('foo');
$userRepository = App::make(App\Repositories\EloquentUserRepository::class, array($this->userMock));
$this->assertEquals('foo', $userRepository->oneUser($this->userMock->id));
}
public function tearDown()
{
Mockery::close();
}
}
I have a problem on unit testing my project.
This is my code:
namespace Way\Storage\HalisahaAccount;
# app/lib/Way/Storage/HalisahaAccount/HalisahaAccountRepositoryInterface.php
interface HalisahaAccountRepositoryInterface {
public function all();
public function find($id);
public function create($input);
}
And the Eloquent repository
namespace Way\Storage\HalisahaAccount;
# app/lib/Way/Storage/HalisahaAccount/EloquentHalisahaAccountRepository.php
use HalisahaAccount;
class EloquentHalisahaAccountRepository implements HalisahaAccountRepositoryInterface {
public function all()
{
return HalisahaAccount::all();
}
public function find($id)
{
return HalisahaAccount::find($id);
}
public function create($input)
{
return HalisahaAccount::create($input);
}
}
And this is my model: HalisahaAccount
class HalisahaAccount extends Eloquent {
/**
* shouldReceive for test
*/
public static function shouldReceive()
{
$class = get_called_class();
$repo = "Way\\Storage\\{$class}\\{$class}RepositoryInterface";
$mock = Mockery::mock($repo);
App::instance($repo, $mock);
return call_user_func_array([$mock, 'shouldReceive'], func_get_args());
}
}
Controller
class HalisahalarController extends BaseController {
protected $halisahaAccount;
public function __construct (HalisahaAccount $halisahaAccount) {
$this->halisahaAccount = $halisahaAccount;
}
public function getIndex(){
$halisahalar = $this->halisahaAccount->all();
return View::make('index',array('halisahalar' => $halisahalar));
}
}
And my test
class HalisahalarControllerTest extends TestCase {
public function tearDown(){
Mockery::close();
}
/**
* halısahaların listelendiği sayfanın testi
*/
public function testGetIndex(){
HalisahaAccount::shouldReceive('all')->once();
$this->client->request('GET', '/halisahalar');
$this->assertViewHas('halisahalar');
}
}
I am running the phpunit test, but getting the this error:
1) HalisahalarControllerTest::testGetIndex
Mockery\Exception\InvalidCountException: Method all() from Mockery_0_Way_Storage_HalisahaAccount_HalisahaAccountRepositoryInterface should be called
exactly 1 times but called 0 times.
Why the mockery dont call my all() method?
I want to test a model in zend project,
<?php
//require_once('CustomModelBase.php');
class Application_Model_User extends Custom_Model_Base {
protected function __construct() {
parent::__construct();
}
static function create(array $data) {
}
static function load($id) {
}
static function find($name, $order=null, $limit=null, $offset=null) {
);
}
}
the model in under application/model folder, it extends a base class Custom_Model_Base which is under the same folder as class User.
In my test, I try to create a new object of User in this way
<?php
class Model_UserTest extends ControllerTestCase
{
protected $user2;
public function setUp() {
parent::setUp();
$this->user2 = new Application_Model_User2();
}
public function testCanDoTest() {
$this->assertTrue(true);
}
}
this is CustomModelBase.php:
abstract class Custom_Model_Base
{
protected function __construct($adapter=null) {}
}
it gives me error, say "PHP Fatal error: Class 'Custom_Model_Base' not found in \application\models\User.php on line 4", the I include "CustomModelBase.php" in User.php,it gives me another error "PHP Fatal error: Call to protected Application_Model_User::__construct() from context 'Model_User2Test' in D:\PHP\apache2\htdocs\ID24_Xiao\tests\application\models \UserTest.php on line 13"
then How could I handle it? can anyone give some suggestion?
If you use 5.3.2 or better you could do it this way:
public function testCanDoTest() {
// set method "nameOfProctedMethod" to accessible on Class App...
$method = new ReflectionMethod(
'Application_Model_User2', 'nameOfProtectedMethod'
);
$method->setAccessible(true);
$this->assertTrue($method->doSomething());
}
You can not call any protected member of class from outside the class.
Either change the access modifier from protected to public
Or create a static function which will give the instance of that class, for e.g.
static function getInstance(){
return new Model_UserTest();
}
As Jeff has said, you can make your constructor testable by making it public like this:
public function __construct() { ...