how do i write test class for controller extension. my code is below.
public AccountAndDetails (ApexPages.k controller)
{
}
Controller extension is just another class. So you want to mimic calling the methods of that class within your test method:
#isTest
private class TestController {
static testMethod void testOne() {
Account acc = new Account(Name = 'Test account');
insert acc;
AccountAndDetails controller = new AccountAndDetails(new ApexPages.StandardController(acc));
controller.methodOne();
controlelr.methodTwo();
// do some asserts
}
}
Create a Test Class with #isTest annotation. Then create some dummy data relevant to the object used in the controller class. Pass the dummy data to the methods defined in the extension class. Write some positive and negative test scenarios with proper assertions.
Related
I'm attempting to employ a custom endpoint that adds a specific claim based on a parameter passed to LocalApiController.
I'm following help at:
http://docs.identityserver.io/en/latest/topics/add_apis.html
I configured startup.cs:
services.AddLocalApiAuthentication(principal =>
{
principal.Identities.First().AddClaim(new Claim("additional_claim", "additional_value"));
return Task.FromResult(principal);
});
and my receiving controller:
[Route("localApi")]
[Authorize(LocalApi.PolicyName)]
public class LocalApiController : ControllerBase
{
public IActionResult Get()
{
var claims = from c in User.Claims select new { c.Type, c.Value };
return new JsonResult(claims);
}
}
[Authorize(LocalApi.PolicyName)] works and fires the helper configured in startup.cs which logically fires before the controllers get method.
I don't see how I can pass the controller's {id} parameter to the helper method (that will become the value of the claim I'm to add, replacing the "additional_value" constant).
Any suggestions?
I have a Controller class, Service class, and Model class. I want to know how I can have access to the same model in both Controller and Service classes.
So for example :
Controller Class :
import { SearchModel } from "../../models/SearchModel";
import { SearchService } from "../../components/SearchService";
export class SearchController {
public searchModel: SearchModel;
static $inject = ['searchService'];
constructor(private searchService:SearchService) {
this.searchService = searchService;
}
public controllerMethod() {
console.log(this.searchModel.searchKeyword); //This works.
this.searchModel.searchKeyword = "CheckIfSharedObject";
this.searchService.serviceMethod();
}
}
Service Class :
import { SearchModel } from "../../models/SearchModel";
export class SearchService {
public searchModel: SearchModel;
constructor() { }
public serviceMethod() {
// This will not work. i.e this wont print 'CheckIfSharedObject'
console.log(this.searchModel.searchKeyword);
}
}
Model Class :
export class SearchModel {
constructor (
public searchKeyword: string
)
}
From the above example, I want controller and service to share the model variable searchKeyword in both the classes.
It works when we pass the model class object to the serviceMethod, but I dont want to do that. Is there a way we can make it work without explicitly passing the Model Class Object to Service class.
I want controller and service to share the model variable searchKeyword in both the classes
It is okay to have model modelled using an angularjs service. That will make the model a singleton that can be shared between the controller and the service.
I would even in fact say that your service should really be the model. That way you will only have "controller" + "service", but feel free to have three things if you want.
how do I access another helper (e.g. FormHelper) from with a new helper method I've built?
class AppHelper extends Helper {
public function generateSpecialInput() {
return $this->Form->input('I\'m special')
}
}
In the above example, Form is the helper I want to use from within my AppHelper::generateSpecialInput method. Should I be passing the FormHelper object into the method, or is there a better way to do it?
see http://book.cakephp.org/2.0/en/views/helpers.html#including-other-helpers
class AppHelper extends Helper {
public $helpers = array('Form');
public function generateSpecialInput() {
return $this->Form->input('I\'m special');
}
}
In the days before I used AutoFixture, I might have done the following arrangement to set up a unit test of a service called CustomerService:
public void TestName()
{
//Arrange
var fakeResponse = new DerivedHttpResponse();
var fakeHandler = new FakeHttpMessageHandler(fakeResponse); // takes HttpResponse
var httpClient = new HttpClient(fakeHandler);
var sut = new CustomerService(httpClient);
// ...
}
This lengthy arrangement seems like a problem that AutoFixture is good at solving. I'd imagine that I'd be able to rewrite that arrangement using AutoFixture too look something like this:
public void TestName([Frozen] DerivedHttpResponse response, CustomerService sut)
{
//Nothing to arrange
// ...
}
My question is, is there a way to configure AutoFixture to do this for me, given the fact that I have many derived HttpResponse types that I want to swap out from test method to test method?
You can use the [Frozen] attribute with the named parameter As:
[Theory, AutoData]
public void TestName(
[Frozen(As = typeof(HttpResponse))] DerivedHttpResponse response,
CustomerService sut)
{
// 'response' is now the same type, and instance,
// with the type that the SUT depends on.
}
The named parameter As specifies the type that the frozen parameter value should be mapped to.
If the HttpResponse type is abstract you will have to create an AutoDataAttribute derived type e.g. AutoWebDataAttribute
public class AutoWebDataAttribute : AutoDataAttribute
{
public AutoWebDataAttribute()
: base(new Fixture().Customize(new WebModelCustomization()))
{
}
}
public class WebModelCustomization : CompositeCustomization
{
public WebModelCustomization()
: base(
new AutoMoqCustomization())
{
}
}
In that case you would use the [AutoWebData] instead.
In CakePHP 2.1 I'm trying to test that the CakeEmail::to() method is called from my model test case with the correct "to" email (In this example: cat#gmail.com).
I want the following test to pass but I get:
Expectation failed for method name is equal to <string:to> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
Here's the code in the Model and the test case:
<?php
// Model/Job.php
App::uses('AppModel', 'Model');
App::uses('CakeEmail', 'Network/Email');
class Job extends AppModel {
public function emailCat() {
$CakeEmail = new CakeEmail();
$CakeEmail->to('cat#gmail.com');
$CakeEmail->subject('hello!');
$CakeEmail->emailFormat('text');
$CakeEmail->config('default');
$CakeEmail->send('hi');
}
}
// Test/Model/JobTest.php
class JobTestCase extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->Job = ClassRegistry::init('Job');
}
public function testEmailCat() {
// I want to assert CakeEmail::to() is called with correct email
$CakeEmail = $this->getMock('CakeEmail' , array('to'));
$CakeEmail->expects($this->once())
->method('to')
->with($this->equalTo('cat#gmail.com'));
$result = $this->Job->emailCat();
}
}
The problem is that you're mocking a completely different class then the one that is actually used on the model. On your model function, you instantiate a brand new email class which will be mocked. Instead, you need to make sure that the CakeEmail object that the model uses is the one mocked.
class Job extends AppModel {
public $CakeEmail = null;
public function emailCat() {
if (!$CakeEmail) {
$this->CakeEmail = new CakeEmail();
}
$this->CakeEmail = new CakeEmail();
$this->CakeEmail->to('cat#gmail.com');
$this->CakeEmail->subject('hello!');
$this->CakeEmail->emailFormat('text');
$this->CakeEmail->config('default');
$this->CakeEmail->send('hi');
}
}
Then update your test case to set the mock object on your Job model.
class JobTestCase extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->Job = ClassRegistry::init('Job');
}
public function testEmailCat() {
// I want to assert CakeEmail::to() is called with correct email
$CakeEmail = $this->getMock('CakeEmail' , array('to'));
$CakeEmail->expects($this->once())
->method('to')
->with($this->equalTo('cat#gmail.com'));
// use mock object instead of creating a brand new one
$this->Job->CakeEmail = $CakeEmail;
$result = $this->Job->emailCat();
}
}