How to refer PageReference method from apex test class - unit-testing

I am new to apex, I have created a button to call the apex class through the visual force page.
Here is my visual force page code.
<apex:page standardController="Opportunity"
extensions="myclass"
action="{!autoRun}">
</apex:page>
Here is my apex class.
public class myclass {
private final Opportunity o;
String tmp;
public myclass(ApexPages.StandardController stdController) {
this.o = (Opportunity)stdController.getRecord();
}
public PageReference autoRun() {
String theId = ApexPages.currentPage().getParameters().get('id');
for (Opportunity o:[select id, name, AccountId, from Opportunity where id =:theId]) {
//Create the Order
Order odr = new Order(
OpportunityId=o.id
,AccountId = o.AccountId
,Name = o.Name
,EffectiveDate=Date.today()
,Status='Draft'
);
insert odr;
tmp=odr.id;
}
PageReference pageRef = new PageReference('/' + tmp);
pageRef.setRedirect(true);
return pageRef;
}
}
I want to create test class. I don't know how to refer PageReference autoRun() method from test class. Guys need help if some one can tell me about test class of this apex class.

You will need to configure the StandardController for the inserted Opportunity. Then pass the StandardController to pass to the constructor before calling the method to test.
E.g.
public static testMethod void testAutoRun() {
Opportunity o = new Opportunity();
// TODO: Populate required Opportunity fields here
insert o;
PageReference pref = Page.YourVisualforcePage;
pref.getParameters().put('id', o.id);
Test.setCurrentPage(pref);
ApexPages.StandardController sc = new ApexPages.StandardController(o);
myclass mc = new myclass(sc);
PageReference result = mc.autoRun();
System.assertNotEquals(null, result);
}

Related

How to test an Update class in apex

Hello I am new to apex and soql, I would like some help on my test class, below is the code i am having trouble with,
public class UpdateMyCard {
#AuraEnabled(cacheable=false)
public static Card__c updateCard(Double Amount){
String userId = UserInfo.getUserId();
Card__c myCard = [SELECT Id, Card_no__c, total_spend__c From Card__c Where OwnerId =:userId];
myCard.total_spend__c = myCard.total_spend__c + Amount;
try{
update myCard;
}catch (Exception e) {
System.debug('unable to update the record due to'+e.getMessage());
}
return myCard;
}
}
Test Class
#isTest
public static void updatecard(){
UpdateMyCard.updateCard(200);
}
Error:
System.QueryException: List has no rows for assignment to SObject
Your code assumes there's already a Card record for this user. And it's exactly 1 record (if you have 2 your query will fail). I'm not sure what's your business requirement. Is it guaranteed there will always be such record? Should the code try to create one on the fly if none found? You might have to make that "updateCard" bit more error-resistant. Is the total spend field marked as required? Because "null + 5 = exception"
But anyway - to fix your problem you need something like that in the test.
#isTest
public static void updatecard(){
Card__c = new Card__c(total_spend__c = 100);
insert c;
UpdateMyCard.updateCard(200);
c = [SELECT total_spend__c FROM Card__c WHERE Id = :c.Id];
System.assertEquals(300, c.total_spend__c);
}

How to fill state/region/subregion selections when page is opened in edit mode?

In Laravel 8/livewire 2/aplinejs I need to fill state/region/subregion, which are tables in db
and I select subregion from priorly selected regions and select regions from priorly selected, like
public function updatedSelectedState($state_id)
{
$this->regionsSelectionArray = Region::getRegionsSelectionArray($state_id, 'A');
$this->detailsForm['state_id'] = $state_id;
}
public function updatedSelectedRegion($region_id)
{
$this->subregionsSelectionArray = Subregion::getSubregionsSelectionByRegionIdArray($region_id);
$this->selectedSubregion = null;
}
it works ok for data inserting , but when I open editor in “edit” mode and I neeed to fill initvalue I
failed how do it. I remember when I made similar tasks with jquery I have common bool var which I set to true
when jquery was inited. And in onChange event I checked this var .
But how can I do it in livewire ?
Thanks in advance!
Call the below functions in your edit method
Example:
public function updatedSelectedState($state_id)
{
$this->changeSelectedState($state_id);
}
public function updatedSelectedRegion($region_id)
{
$this->changeSelectedRegion($region_id);
}
public function changeSelectedState($state_id){
$this->regionsSelectionArray = Region::getRegionsSelectionArray($state_id, 'A');
$this->detailsForm['state_id'] = $state_id;
}
public function changeSelectedRegion($region_id)
{
$this->subregionsSelectionArray = Subregion::getSubregionsSelectionByRegionIdArray($region_id);
$this->selectedSubregion = null;
}
public function edit(){
// $state_id = provide your state id here
// $region_id = provide your region id here
$this->changeSelectedState($state_id);
$this->changeSelectedRegion($region_id);
}

Sales force - Test Apex Class List

I made an Apex Class in the Sandbox to call a List.
Now I need to implement it in the production. To do so, I need to implement a Test with at least 75% Success.
The Apex Class produces a List of “dfind_Research_Projekt__c” from which “dfind_Potenzieller_Kandidat__c “ is the actual record, I use this list to make an iteration and show all the “dfind_Research_Projekt__c” on the page from “dfind_Potenzieller_Kandidat__c “.
This is my Apex Class:
public with sharing class dfind_Pot_Job_Application_List {
#AuraEnabled
//Get Pot Job Application List
public static List<dfind_Research_Projekt__c> getJobApp(Id recordId) {
List<dfind_Research_Projekt__c> JobAppList = [Select Id, Name, dfind_Potenzieller_Kandidat__c, dfind_Job__c,
LastModifiedById, dfind_Bewerbungsdatum__c, dfind_Job_Name__c,
OwnerId
from dfind_Research_Projekt__c
where dfind_Potenzieller_Kandidat__c = :recordId
ORDER BY dfind_Bewerbungsdatum__c DESC NULLS LAST];
return JobAppList;
}
//Get User
#AuraEnabled
public static user fetchUser(){
User u = [select id,Name from User where id =: userInfo.getUserId()];
return u;
}
}
This is my test:
#isTest
public class TESTdfind_pot_job_app {
static testMethod void myUnitTest() {
//Create Data for Customer Objet
cxsrec__Potential_candidate__c objKandi = new cxsrec__Potential_candidate__c();
objKandi.Name = 'Test Kandidat';
insert objKandi;
//Create List
List<dfind_Research_Projekt__c> listOfPotApp = new List<dfind_Research_Projekt__c>{
new dfind_Research_Projekt__c(Name='Test Appplication'
, dfind_Job__c='a0w0X000008KKB5QAO'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 1'
, dfind_Job__c='a0w1x0000013aSRAAY'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 2'
, dfind_Job__c='a0w1x000000JJSBAA4'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ')
};
insert(listOfPotApp);
Test.startTest();
// Starts the scope of test
// Now check if it is giving desired results using system.assert
// Statement.New invoice should be created
List<dfind_Research_Projekt__c> JobAppList = new List<dfind_Research_Projekt__c>(listOfPotApp);
Test.stopTest(); // Ends the scope of test
for(Integer i=0;i<JobAppList.Size();i++) {
system.assertEquals(JobAppList[i].dfind_Potenzieller_Kandidat__c,objKandi.Id);
System.debug(i + 'Kandidat: ' + JobAppList[i].dfind_Potenzieller_Kandidat__c + ';');
System.debug(i + ': ' + objKandi.Id + ';');
}
system.assertEquals(1,1);
}
}
The hard-coded Ids in your unit test won't work. Your unit tests executes in an isolated data context and must generate all of its own test data.
As written, this test doesn't really do anything. It does not invoke the code you intend to test, as it must to evaluate its behavior and obtain code coverage. You'd need to call fetchUser() and getJobApp() at some point and write assertions about their return values. The assertions that are currently present are all tautological; they're guaranteed to pass and provide no information.
See How do I write an Apex unit test? on Salesforce Stack Exchange for introductory resources.

Running BeamSql WithoutCoder or Making Coder Dynamic

I am reading data from file and converting it to BeamRecord But While i am Doing Query on that it Show Error-:
Exception in thread "main" java.lang.ClassCastException: org.apache.beam.sdk.coders.SerializableCoder cannot be cast to org.apache.beam.sdk.coders.BeamRecordCoder
at org.apache.beam.sdk.extensions.sql.BeamSql$QueryTransform.registerTables(BeamSql.java:173)
at org.apache.beam.sdk.extensions.sql.BeamSql$QueryTransform.expand(BeamSql.java:153)
at org.apache.beam.sdk.extensions.sql.BeamSql$QueryTransform.expand(BeamSql.java:116)
at org.apache.beam.sdk.Pipeline.applyInternal(Pipeline.java:533)
at org.apache.beam.sdk.Pipeline.applyTransform(Pipeline.java:465)
at org.apache.beam.sdk.values.PCollectionTuple.apply(PCollectionTuple.java:160)
at TestingClass.main(TestingClass.java:75)
But When I am Providing it a Coder Then It Runs Perfectly.
I am little confused that if I am reading data from a file the file data schema changes on every run because I am using templates so is there any way I can use Default Coder or Without Coder, i can Run the Query.
For Reference Code is Below Please Check.
PCollection<String> ReadFile1 = PBegin.in(p).apply(TextIO.read().from("gs://Bucket_Name/FileName.csv"));
PCollection<BeamRecord> File1_BeamRecord = ReadFile1.apply(new StringToBeamRecord()).setCoder(new Temp().test().getRecordCoder());
PCollection<String> ReadFile2= p.apply(TextIO.read().from("gs://Bucket_Name/FileName.csv"));
PCollection<BeamRecord> File2_Beam_Record = ReadFile2.apply(new StringToBeamRecord()).setCoder(new Temp().test1().getRecordCoder());
new Temp().test1().getRecordCoder() --> Returning HardCoded BeamRecordCoder Values Which I need to fetch at runtime
Conversion From PColletion<String> to PCollection<TableRow> is Below-:
Public class StringToBeamRecord extends PTransform<PCollection<String>,PCollection<BeamRecord>> {
private static final Logger LOG = LoggerFactory.getLogger(StringToBeamRecord.class);
#Override
public PCollection<BeamRecord> expand(PCollection<String> arg0) {
return arg0.apply("Conversion",ParDo.of(new ConversionOfData()));
}
static class ConversionOfData extends DoFn<String,BeamRecord> implements Serializable{
#ProcessElement
public void processElement(ProcessContext c){
String Data = c.element().replaceAll(",,",",blank,");
String[] array = Data.split(",");
List<String> fieldNames = new ArrayList<>();
List<Integer> fieldTypes = new ArrayList<>();
List<Object> Data_Conversion = new ArrayList<>();
int Count = 0;
for(int i = 0 ; i < array.length;i++){
fieldNames.add(new String("R"+Count).toString());
Count++;
fieldTypes.add(Types.VARCHAR); //Using Schema I can Set it
Data_Conversion.add(array[i].toString());
}
LOG.info("The Size is : "+Data_Conversion.size());
BeamRecordSqlType type = BeamRecordSqlType.create(fieldNames, fieldTypes);
c.output(new BeamRecord(type,Data_Conversion));
}
}
}
Query is -:
PCollectionTuple test = PCollectionTuple.of(
new TupleTag<BeamRecord>("File1_BeamRecord"),File1_BeamRecord)
.and(new TupleTag<BeamRecord>("File2_BeamRecord"), File2_BeamRecord);
PCollection<BeamRecord> output = test.apply(BeamSql.queryMulti(
"Select * From File1_BeamRecord JOIN File2_BeamRecord "));
Is thier anyway i can make Coder Dynamic or I can Run Query with Default Coder.

APEX Test Class 0% code coverage

I am trying to deploy some code that does something simple, when the user clicks on the accept button, it checks a checkbox (I have a workflow set up on the checkbox) and then I need it to redirect me to a thank you page. At the moment I don't know if my code is correct so I need to get the test correct to test it.
My Apex class:
public class proposalCon {
ApexPages.StandardController stdCtrl;
Public List <PPM_Project__c> PPM_Project_List {get;set;}
public proposalCon(ApexPages.StandardController controller) {
stdCtrl= controller;
PPM_Project_List = [ select Short_Description__c from PPM_Project__c ];
}
public PageReference save(){
upsert PPM_Project_List;
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
return reRend;
}
}
And here is my test attempt:
#isTest
private class proposalConTest{
static testMethod void testProposalCon() {
// List of Message
List <PPM_Project__c> PPM_ProjectList = new List<PPM_Project__c>();
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DE123'
));
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test 2' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DEf123'
));
insert PPM_ProjectList;
Account account = new Account(Name='Test Co Pty Ltd');
insert account;
Contact contact = new Contact(firstName='TestFN',LastName='TestLN',email='testfn.testln#test.com',AccountId=account.Id);
insert contact;
// ** Start Testing ***/
proposalCon controller = new proposalCon();
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
PPM_ProjectList = [ select Short_Description__c from PPM_Project__c ];
}
}
I have been trying with no luck and any help would be greatly appreciated.
Thank you.
Joe
You need to instantiate a Standard Controller (feeding it a list of PPM Projects) and then instantiate your custom controller extension - like this:
PPM_Project__c proj = new PPM_Project__c() //you may need further parameters here.
ApexPages.StandardController stdController = new apexPages.StandardController(proj);
proposalCon controller = new proposalCon (stdController);
Then you can save, rerender as you like. Let me know if this works - I haven't executed this code, but this is how I create my own controller extension tests.
This should at least compile. However, I think you may really want a StandardSetController.
The docs are here:
SalesforceDocs
To make a testmethod for the StandardSetController, use something like this:
//instantiate the ApexPages.StandardSetController with an array of projects
ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(PPM_ProjectList);
//create custom controller with the StandardSetController as a param
ProposalCon ext = new ProposalCon(stdSetController);
This guy has more details on how to create a test method for a StandardSetController (and other controllers)