• Mayur Mehta
  • NEWBIE
  • 10 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 3
    Replies
I am stuck with Data Integration Specialist superbadge challenge #4. While trying to run the test i am getting an error  'Methods defined as TestMethod do not support Web service callouts'. Below are my code:

@IsTest
public class ProjectCalloutServiceMock implements HttpCallOutMock{
   //Implement http mock callout here
    public HttpResponse respond(HttpRequest req)
    {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatus('OK');
        res.setStatusCode(201);
        return res;
    }
}

@Istest
public class ProjectCalloutServiceMockFailure implements HttpCallOutMock {
   //Implement http mock callout failure here
   public HttpResponse respond(HttpRequest req)
    {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatus('Error');
        res.setStatusCode(500);
        return res;
    }
}

@isTest
private class ProjectCalloutServiceTest {
  //Implement mock callout tests here
  @testsetup
  public static void setupdata()
  {
      List<Opportunity> oppsToInsert = new List<Opportunity>();
      
      Account acct = new Account();
      acct.Name='test Account';
      insert acct;
      
      Opportunity opp1 = new Opportunity();
      opp1.Name = 'Opp1';
      opp1.Type='New Customer';
      opp1.AccountId = acct.id;
      opp1.amount=500;
      opp1.CloseDate = date.today();
      opp1.StageName = 'Prospecting';
      oppsToInsert.add(opp1);
      
      Opportunity opp2 = new Opportunity();
      opp2.Name = 'Opp2';
      opp2.Type='New Customer';
      opp2.AccountId = acct.id;
      opp2.amount=2500;
      opp2.CloseDate = date.today().addDays(-3);
      opp2.StageName = 'Prospecting';
      oppsToInsert.add(opp2);
      
      insert oppsToInsert;
      
      ServiceTokens__c st = new ServiceTokens__c();
      st.Name = 'ProjectServiceToken';
      st.Token__c = 'thisistesttoken';
      insert st;
      
  }
    
   @istest
    public static void testSuccessMessage()
    {
        Opportunity oppList = [Select Id from Opportunity where Name='Opp1' limit 1];
        List<Id> oppIds = new List<Id>();
        oppIds.add(oppList.Id);
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock());
        test.startTest();
            ProjectCalloutService.postOpportunityToPMS(oppIds);
        test.stopTest();
        oppList = [Select StageName from Opportunity where Name='Opp1' limit 1];
        system.assertEquals('Submitted Project',oppList.StageName);
    }
    
    @istest
    public static void testFailureMessage()
    {
        Opportunity oppList = [Select Id from Opportunity where Name='Opp2' limit 1];
        List<Id> oppIds = new List<Id>();
        oppIds.add(oppList.Id);
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure());
        test.startTest();
            ProjectCalloutService.postOpportunityToPMS(oppIds);
        test.stopTest();
        oppList = [Select StageName from Opportunity where Name='Opp2' limit 1];
        system.assertEquals('Resubmit Project',oppList.StageName);
    }
}
Guys-

I am testing an apex class (projectCalloutService). I took a different approach and made some class variables static because to avoid having to pass any parameters to queueable interface ( just to try it out). However, my test methods assertion failed in projectCalloutServiceTest class. I use VScode for my dev work and I tried to debug using Apex replay debugger and found out that my Static Variables of the projectCalloutService class becomes null and I dont understand why. Any help is appreciated and most likely I am making a dumb mistake somewhere.. thanks in advance!
 
public class ProjectCalloutService {
    static Opportunity opportunityObj;
    static Opportunity opp ;
    
    
    @InvocableMethod(label='Post Opportunity To PMS' description='Synchronize Outbound Project Data')  
    public static void PostOpportunityToPMS(List<Id> opportunityIds) {
        Opportunity opp = [SELECT Amount,CloseDate,Id,Name,StageName,Account.Name FROM Opportunity WHERE Id =: opportunityIds.get(0)] ; 
        Opportunity opportunityObj;
        ID newJobId = System.enqueueJob(new QueueablePMSCall());
        System.debug(newJobId);
    }
    
    @Future(callout=true) 
    private static void makeServiceCall( ){
        
        opportunityObj = opp;
        JSONGenerator gen = JSON.createGenerator(true); // DO NOT USE JSON as variable (Case Insensitive)
        gen.writeStartObject();
        gen.writeStringField('opportunityId', opp.Id);
        gen.writeStringField('opportunityName', opp.Name);
        gen.writeStringField('accountName', opp.account.Name);
        gen.writeDateField('closeDate', opp.closeDate);
        gen.writeNumberField('amount', opp.amount);            
        gen.writeEndObject();      
        String jsonReq= gen.getAsString();
        System.debug('jsonReq: ' + jsonReq);
        
        
        
        
        ServiceTokens__c token= ServiceTokens__c.getValues('ProjectServiceToken');
        System.debug('TOKEN is :'+token.Token__c);
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:ProjectService/'+token.Token__c);
        System.debug('ENDPOINT is :'+'callout:ProjectService/'+token.Token__c);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(jsonReq);
        HttpResponse response = http.send(request);
        System.debug('RESPONSE is :'+response);
        
        
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                         response.getStatusCode() + ' ' + response.getStatus());
            opportunityObj.StageName='Resubmit Project';
            upsert opportunityObj;
            
        } else {
            
            System.debug(response.getBody());
            opportunityObj.StageName='Submitted Project';
            upsert opportunityObj;
            
        }
        
        
        
    }
    
    
    
    // Queue 
    class QueueablePMSCall implements Queueable,Database.AllowsCallouts
    {
        
        public void execute(QueueableContext context) {
            
            makeServiceCall();
        }
        
    }
    
    
}
@isTest
private class ProjectCalloutServiceTest {
    
    @TestSetup
    static void makeData(){
        //create the Custom Settings
        ServiceTokens__c servToken = new ServiceTokens__c();
        servToken.Name = 'ProjectServiceToken';
        servToken.Token__c = 'jkhasbdha';
        insert servToken;
        
        Account testAcct = new Account(Name='TestOpAct');
        insert testAcct;
        
        List<Opportunity> oppList = new list<Opportunity>();
        Opportunity testOpp1 = new Opportunity(Name='TestOp1',StageName='Closed Won',Type='New Project',CloseDate=system.today(), AccountId = testAcct.id, Amount=50000);     
        Opportunity testOpp2 = new Opportunity(Name='TestOp2',StageName='Closed Won',Type='New Project',CloseDate=system.today(), AccountId = testAcct.id, Amount=50000);
        System.debug(testOpp1);
        oppList.add(testOpp1);
        oppList.add(testOpp2);
        upsert opplist; 
        System.debug(opplist);
        
        
        
        
        
        System.debug(testOpp1);
        
    }
    
    
    
    @isTest 
    public static void successTest(){    
        
        List<Id> oppIds = new List<Id>(new Map<Id,Opportunity>([SELECT Name,Id FROM Opportunity WHERE Name = 'Testop1']).keySet());
        
        // If an HTTP callout is invoked in test context, the callout is not made. Instead, you receive the mock response that you specify in the respond method implementation in AnimalLocatorMock.
        // Set mock callout class 
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMock()); 
        ProjectCalloutService.PostOpportunityToPMS(oppIds);
        Test.stopTest();
        
        
        Opportunity opp = [SELECT Name, StageName FROM Opportunity where Name='TestOp1'];
        System.assert(opp.StageName=='Submitted Project');
        
        
    }
    
    @isTest 
    public static void failureTest(){
        
        List<Id> oppIds = new List<Id>(new Map<Id,Opportunity>([SELECT Name,Id FROM Opportunity WHERE Name = 'Testop2']).keySet());
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ProjectCalloutServiceMockFailure()); 
        ProjectCalloutService.PostOpportunityToPMS(oppIds);
        Test.stopTest();
        Opportunity opp = [SELECT Name, StageName FROM Opportunity where Name='TestOp2'];
        System.assert(opp.StageName=='Resubmit Project');
        
        
        
    }
    
    
    
}

 
I am always getting this error "ContactDetails$controller$locationChange [Cannot read property 'indexOf' of undefined] Failing descriptor: {ContactDetails$controller$locationChange}" Not sure what is wrong, can you please help

My component is 

<aura:component controller="ContactController">

    <aura:attribute name="contact" type="Contact" default="{'sobjectType': 'Contact'}"/>
    <aura:handler event="aura:locationChange" action="{!c.locationChange}"/>

    <div class="details">
        <h1>{!v.contact.Name}</h1>
        <h3>{!v.contact.Account.Name}</h3>
        <h3>{!v.contact.Title}</h3>
        <p>{!v.contact.Phone}</p>
        {!v.contact.MobilePhone}
    </div>

</aura:component>



and Controller is



({
    locationChange : function(component, event, helper) {
        
        var token=event.getParam("token");
        if(token.indexOf('contact/')===0)
        {
            var contactId=token.substr(token.indexOf('/')+1);
            var action=component.get("c.findById");
            action.setParams({"contactId":contactId});
        }
        action.setCallback(this,function(response){
            
            component.set("v.contacttt",response.getReturnValue());
        })
    $A.enqueueAction(action);
    }
})

This is the trailhead challenge I'm working on.
Create a report of Opportunities grouped by Type. Then follow the dashboard and share a snapshot on Chatter.
Name the report 'Opportunities by Type' and save it to the 'Unfiled Public Reports' folder.
The report must be of type Opportunities.
The report format must be a Summary report.
The report must be grouped by 'Type'.
The date range should be for All Time.
You can include any columns you like, but must include 'Amount' as one of the columns.
Create a dashboard named 'Opportunities Dashboard' and save it to the 'My Personal Dashboards' folder.
Create a dashboard component on the dashboard using the report you just created.
Set the header to 'Opptys by Type' and the title to 'For all time' for the dashboard component.
Use the horizontal bar chart dashboard component, and ensure the record count is displayed on the x-axis.
Follow the 'Opportunities Dashboard' dashboard in Chatter. Make sure that Feed Tracking is enabled for Dashboards first.
Post a snapshot of the 'Opptys by Type' dashboard component to Dashboard Chatter feed.

But I'm getting the following error when I check if the challenge has been completed
Challenge Not yet complete... here's what's wrong: 
The dashboard snapshot post to Chatter was not found.
Can someone hepl me?
If possible post the snapshots?