Open MS167978 opened 1 month ago
What are lines it's not covering?
On Mon, Sep 30, 2024 at 1:55 PM maheshsaboli @.***> wrote:
I have added all the provided Apex classes and executed the test class. In my org, the current code coverage is 86%. However, I am unable to reach 90% coverage because the test class does not cover the following code in the Apex class.
Apex Copy code:-
} catch (Exception e) { System.debug('Error: ' + e.getMessage()); statusCode = 500; // Internal Server Error }
Could you please help me resolve this issue?"
— Reply to this email directly, view it on GitHub https://github.com/LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHBACMEGM42TRU3PRT6B27TZZEDIFAVCNFSM6AAAAABPCXP3ROVHI2DSMVQWIX3LMV43ASLTON2WKOZSGU2TKOJSHEYDQMQ . You are receiving this because you are subscribed to this thread.Message ID: <LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4@ github.com>
Line numbers 17 and 19 are highlighted below:-
send me your both class and test class please
On Mon, Sep 30, 2024 at 3:16 PM MS @.***> wrote:
Line number 17 and 19 which are highlighted below:-
} catch (Exception e) { System.debug('Error: ' + e.getMessage()); statusCode = 500; // Internal Server Error }
— Reply to this email directly, view it on GitHub https://github.com/LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4#issuecomment-2382643298, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHBACMB77ICSEXAGYGBFMWDZZEMYJAVCNFSM6AAAAABPCXP3ROVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGOBSGY2DGMRZHA . You are receiving this because you commented.Message ID: <LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4/2382643298 @github.com>
Apex Class:- public class RewardsCalloutService { public static Integer submitUsersForRewardCallout(String jsonBody) { HttpRequest req = new HttpRequest(); req.setEndpoint('callout:BalancedLiving/rewards'); req.setMethod('POST'); req.setHeader('Content-Type', 'application/json'); req.setBody(jsonBody);
Http http = new Http();
HttpResponse res;
Integer statusCode;
try {
res = http.send(req);
statusCode = res.getStatusCode();
System.debug('Response Status: ' + statusCode);
System.debug('Response Body: ' + res.getBody());
} catch (Exception e) {
System.debug('Error: ' + e.getMessage());
statusCode = 500; // Internal Server Error
}
return statusCode;
}
}
Test Class:- @isTest public class RewardsCalloutServiceTest { @isTest static void testSubmitUsersForRewardCallout() { Test.setMock(HttpCalloutMock.class, new RewardsCalloutServiceMock());
// Create test data for Wellness Journey
List<Wellness_Journey__c> journeys = new List<Wellness_Journey__c>();
User testUser = [SELECT Id, Name, Username, Email FROM User WHERE Id = :UserInfo.getUserId()];
for (Integer i = 0; i < 12; i++) {
Wellness_Journey__c journey = new Wellness_Journey__c(
OwnerId = testUser.Id
);
journeys.add(journey);
}
insert journeys;
Test.startTest();
Database.executeBatch(new WellnessJourneyRewardsBatch());
Test.stopTest();
// Assertions to validate the behavior can be added here
Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(JSON.serialize(journeys));
System.assertEquals(200, statusCode, 'The HTTP status code should be 200');
}
}
Mock Test class:- @isTest global class RewardsCalloutServiceMock implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest req) { HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"status":"success"}'); res.setStatusCode(200); return res; } }
Let me see
On Mon, 30 Sep 2024 at 3:21 PM, MS @.***> wrote:
Apex Class:- public class RewardsCalloutService { public static Integer submitUsersForRewardCallout(String jsonBody) { HttpRequest req = new HttpRequest(); req.setEndpoint('callout:BalancedLiving/rewards'); req.setMethod('POST'); req.setHeader('Content-Type', 'application/json'); req.setBody(jsonBody);
Http http = new Http(); HttpResponse res; Integer statusCode; try { res = http.send(req); statusCode = res.getStatusCode(); System.debug('Response Status: ' + statusCode); System.debug('Response Body: ' + res.getBody()); } catch (Exception e) { System.debug('Error: ' + e.getMessage()); statusCode = 500; // Internal Server Error } return statusCode;
}
}
Test Class:- @istest https://github.com/istest public class RewardsCalloutServiceTest { @istest https://github.com/istest static void testSubmitUsersForRewardCallout() { Test.setMock(HttpCalloutMock.class, new RewardsCalloutServiceMock());
// Create test data for Wellness Journey List<Wellness_Journey__c> journeys = new List<Wellness_Journey__c>(); User testUser = [SELECT Id, Name, Username, Email FROM User WHERE Id = :UserInfo.getUserId()]; for (Integer i = 0; i < 12; i++) { Wellness_Journey__c journey = new Wellness_Journey__c( OwnerId = testUser.Id ); journeys.add(journey); } insert journeys; Test.startTest(); Database.executeBatch(new WellnessJourneyRewardsBatch()); Test.stopTest(); // Assertions to validate the behavior can be added here Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(JSON.serialize(journeys)); System.assertEquals(200, statusCode, 'The HTTP status code should be 200');
}
}
Mock Test class:- @istest https://github.com/istest global class RewardsCalloutServiceMock implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest req) { HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"status":"success"}'); res.setStatusCode(200); return res; } }
— Reply to this email directly, view it on GitHub https://github.com/LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4#issuecomment-2382653771, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHBACMCUXIXWWOHKWTGEGALZZENLRAVCNFSM6AAAAABPCXP3ROVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGOBSGY2TGNZXGE . You are receiving this because you commented.Message ID: <LogicLuminaryy/Solution-Apex-Callouts-Superbadge-Unit-/issues/4/2382653771 @github.com>
Sure, Thank you.
`@IsTest public class RewardsCalloutServiceTest {
@IsTest
static void testSubmitUsersForRewardCalloutSuccess() {
// Setup mock response for the HTTP callout
Test.setMock(HttpCalloutMock.class, new RewardsCalloutMockSuccess());
// Example JSON body to send
String jsonBody = '{"userId": "001XX000003DHPc"}';
// Call the method
Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(jsonBody);
// Verify the status code is as expected (mocked 200)
System.assertEquals(200, statusCode, 'The status code should be 200 for a successful callout');
}
@IsTest
static void testSubmitUsersForRewardCalloutFailure() {
// Setup mock response for the HTTP callout to simulate failure
Test.setMock(HttpCalloutMock.class, new RewardsCalloutMockFailure());
// Example JSON body to send
String jsonBody = '{"userId": "001XX000003DHPc"}';
// Call the method
Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(jsonBody);
// Verify the status code is as expected (mocked failure 500)
System.assertEquals(500, statusCode, 'The status code should be 500 for a failed callout');
}
// Mock class for a successful callout
private class RewardsCalloutMockSuccess implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"message": "Success"}');
return res;
}
}
// Mock class for a failed callout
private class RewardsCalloutMockFailure implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(500);
res.setBody('{"message": "Internal Server Error"}');
return res;
}
}
} `
with this code the code coverage of the WellnessJourneyRewardsBatch turns to 0%
you can provide me access to you org i can take look then
Hi @danielFuentes01,
Use the below code provided.
* RewardsCalloutServiceMock**
@isTest
global class RewardsCalloutServiceMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
* RewardsCalloutServiceTest**
@isTest
public class RewardsCalloutServiceTest {
@isTest static void testSubmitUsersForRewardCallout() {
Test.setMock(HttpCalloutMock.class, new RewardsCalloutServiceMock());
// Create test data for Wellness Journey
List<Wellness_Journey__c> journeys = new List<Wellness_Journey__c>();
User testUser = [SELECT Id, Name, Username, Email FROM User WHERE Id = :UserInfo.getUserId()];
for (Integer i = 0; i < 12; i++) {
Wellness_Journey__c journey = new Wellness_Journey__c(
OwnerId = testUser.Id
);
journeys.add(journey);
}
insert journeys;
Test.startTest();
Database.executeBatch(new WellnessJourneyRewardsBatch());
Test.stopTest();
// Assertions to validate the behavior can be added here
Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(JSON.serialize(journeys));
System.assertEquals(200, statusCode, 'The HTTP status code should be 200');
}
@isTest static void testException() {
Test.setMock(HttpCalloutMock.class, new RewardsCalloutServiceErrorMock());
Test.startTest();
Database.executeBatch(new WellnessJourneyRewardsBatch());
Test.stopTest();
String journeys = 'Test';
// Assertions to validate the behavior can be added here
Integer statusCode = RewardsCalloutService.submitUsersForRewardCallout(JSON.serialize(journeys));
System.debug(statusCode);
System.assertEquals(500, statusCode, 'The HTTP status code should be 200');
}
}
** RewardsCalloutService**
public class RewardsCalloutService {
public static Integer submitUsersForRewardCallout(String jsonBody) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:BalancedLiving/rewards');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(jsonBody);
Http http = new Http();
HttpResponse res;
Integer statusCode;
/*try {
res = http.send(req);
statusCode = res.getStatusCode();
System.debug('Response Status: ' + statusCode);
System.debug('Response Body: ' + res.getBody());
} catch (Exception e) {
System.debug('Error: ' + e.getMessage());
statusCode = 500; // Internal Server Error
}*/
res = http.send(req);
statusCode = res.getStatusCode();
System.debug('Response Status: ' + statusCode);
System.debug('Response Body: ' + res.getBody());
return statusCode;
}
}
* WellnessJourneyRewardsBatch**
global class WellnessJourneyRewardsBatch implements Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts {
global Database.QueryLocator start(Database.BatchableContext BC) {
Date startDate = getStartDate();
Date endDate = getEndDate();
String query = 'SELECT Id,Name,OwnerId, Owner.Name, Owner.Email, Owner.Username FROM Wellness_Journey__c WHERE Status__c = \'Complete\' AND Completion_Date__c >= :startDate AND Completion_Date__c <= :endDate ORDER BY OwnerId, Completion_Date__c';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Wellness_Journey__c> scope) {
Map<Id, Integer> userGoalCountMap = new Map<Id, Integer>();
Set<Id> uniqueUserId = new Set<Id>();
//Array of JSON objects
List<Map<String, Object>> usersListMap = new List<Map<String, Object>>();
// Initialize the map with user IDs and set the initial count to 0
for (Wellness_Journey__c journey : scope) {
userGoalCountMap.put(journey.OwnerId, 0);
}
for (Wellness_Journey__c journey : scope) {
// Calculate the number of journeys completed by each user
Integer goalCount = userGoalCountMap.get(journey.OwnerId);
goalCount++;
userGoalCountMap.put(journey.OwnerId,goalCount);
// Check if the user has completed atleast 12 goals in the quarter and hasn't already been added to the array
if(userGoalCountMap.get(journey.OwnerId)>=12 && !uniqueUserId.contains(journey.OwnerId)){
Map<String, Object> userObj = new Map<String, Object>();
uniqueUserId.add(journey.OwnerId);
//Build JSON object
userObj.put('userId',journey.OwnerId);
userObj.put('fullName',journey.Owner.Name);
userObj.put('email',journey.Owner.Email);
userObj.put('username',journey.Owner.Username);
//Add to array
usersListMap.add(userObj);
}
}
//Serialize JSON
String jsonBody = JSON.serialize(usersListMap);
//Invoke Callout
Integer responseCode = RewardsCalloutService.submitUsersForRewardCallout(jsonBody);
System.debug('HTTP Response Code: ' + responseCode);
}
global void finish(Database.BatchableContext BC) {
// Perform finish operations
}
// Helper methods to get the start and end date of the quarter
public static Date getStartDate() {
Date today = Date.today();
Integer currentYear = today.year();
Integer currentMonth = today.month();
Integer previousQuarterStartMonth = ((currentMonth - 1) / 3) * 3 + 1 - 3;
if (previousQuarterStartMonth <= 0) {
previousQuarterStartMonth += 12;
currentYear--;
}
Date previousQuarterStartDate = Date.newInstance(currentYear, previousQuarterStartMonth, 1);
return previousQuarterStartDate;
}
public static Date getEndDate() {
Date previousQuarterStartDate = getStartDate();
Date previousQuarterEndDate = previousQuarterStartDate.addMonths(3).addDays(-1);
return previousQuarterEndDate;
}
}
* WellnessJourneyRewardsBatchTest**
@isTest
public class WellnessJourneyRewardsBatchTest {
@testSetup
static void setup() {
// Create test users
User testUser1 = new User(
FirstName = 'Test',
LastName = 'User1',
Email = 'testuse4354647r1@example.com',
Username = 'testuser323231@example.com',
Alias = 'tuser1',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name='Standard User' LIMIT 1].Id,
LanguageLocaleKey = 'en_US'
);
insert testUser1;
User testUser2 = new User(
FirstName = 'Test',
LastName = 'User2',
Email = 'testuse232425r2@example.com',
Username = 'testuser232323232@example.com',
Alias = 'tuser2',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = [SELECT Id FROM Profile WHERE Name='Standard User' LIMIT 1].Id,
LanguageLocaleKey = 'en_US'
);
insert testUser2;
// Create test Wellness_Journey__c records
List<Wellness_Journey__c> journeys = new List<Wellness_Journey__c>();
for (Integer i = 0; i < 13; i++) {
journeys.add(new Wellness_Journey__c(
Name = 'Journey ' + i,
OwnerId = testUser1.Id,
Status__c = 'Complete',
Completion_Date__c = Date.today().addDays(-90)
));
}
for (Integer i = 0; i < 5; i++) {
journeys.add(new Wellness_Journey__c(
Name = 'Journey ' + (13 + i),
OwnerId = testUser2.Id,
Status__c = 'Complete',
Completion_Date__c = Date.today().addDays(-90)
));
}
insert journeys;
}
@isTest
static void testWellnessJourneyRewardsBatch() {
// Mocking the HTTP response for RewardsCalloutService
Test.setMock(HttpCalloutMock.class, new RewardsCalloutServiceMock());
// Execute the batch
Test.startTest();
WellnessJourneyRewardsBatch batch = new WellnessJourneyRewardsBatch();
Database.executeBatch(batch);
Test.stopTest();
// Verify that the batch executed correctly
// We can verify by checking debug logs or using other assert statements
// Ensure that the correct number of journeys were processed
List<Wellness_Journey__c> processedJourneys = [SELECT Id FROM Wellness_Journey__c WHERE Status__c = 'Complete'];
System.assertEquals(18, processedJourneys.size());
}
}
please let me know if it helped to resolve your issue.
I have added all the provided Apex classes and executed the test class. In my org, the current code coverage is 86%. However, I am unable to reach 90% coverage because the test class does not cover the following code in the Apex class.
Apex Copy code:-
Could you please help me resolve this issue?"