Being new to salesforce i'm trying to make a prod deployment but it is failing because of code coverage issue.
These are the apex classes that i wrote:
HttpCallOut.apxc
public with sharing class HttpCallOut {
#future(callout=true)
public static void callService(string endpoint, string method, string body) {
try {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:API_SERVICES' + endpoint);
request.setMethod(method);
request.setHeader('content-type', 'application/json');
request.setBody(body);
HttpResponse response = http.send(request);
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus() + ' ' + response.getBody());
throw new CustomException('Error calling endpoint ' + endpoint + 'Status Code: ' + response.getStatusCode() + 'Status: ' + response.getStatus()+ 'Response Body: ' + response.getStatus());
}
return;
} catch (CalloutException calloutException) {
throw new CustomException('Error in HttpCallOut callService: ', calloutException);
}
}
}
CustomException.Apxc
public class CustomException extends Exception {
}
HandleUpdateOnReturnRefundCase
public with sharing class HandleUpdateOnReturnRefundCase {
private HttpCallOut httpCallOut = new HttpCallOut();
#InvocableMethod
public static void handleUpdateOnReturnRefundCase(List<Id> caseIds) {
List<Case> updatedCases = [select id, Decision__c, ZoroCaseIdentifier__c, Type, Description, ReturnOptions__c from Case where Id in :caseIds];
Case updatedCase = updatedCases.get(0);
if((updatedCase.Decision__c == 'Approved' && updatedCase.ReturnOptions__c != null) || updatedCase.Decision__c == 'Rejected') {
httpCallOut.callService(
'/salesforce-case-updated',
'POST',
genPayload(updatedCase.id, updatedCase.ZoroCaseIdentifier__c, updatedCase.Type)
);
} else {
throw new CustomException('Cannot update the case, please fill all required fields');
}
update updatedCases;
}
private static String genPayload(Id caseId, String zoroCaseIdentifier, String caseType) {
CasePayload casePayload = new CasePayload();
casePayload.caseId = caseId;
casePayload.caseType = caseType;
casePayload.zoroCaseIdentifier = zoroCaseIdentifier;
return JSON.serialize(casePayload);
}
}
CasePayload.Apxc
public class CasePayload {
public Id caseId {
get { return caseId; }
set { caseId = value; }
}
public String zoroCaseIdentifier {
get { return zoroCaseIdentifier; }
set { zoroCaseIdentifier = value; }
}
public String caseType {
get { return caseType; }
set { caseType = value; }
}
}
For above apex classes i have written test cases:
HandleUpdateOnReturnRefundCaseTest
#isTest
private class HandleUpdateOnReturnRefundCaseTest {
static testMethod void testApprovedReturnRefundCase() {
Case mockCase = new Case();
mockCase.Type = 'Request Return';
insert mockCase;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new HttpCalloutSuccessTest());
mockCase.Decision__c = 'Approved';
mockCase.ReturnOptions__c = 'FOC without Returned Items';
update mockCase;
Test.stopTest();
List<Case> cases = [SELECT Id, Decision__c FROM Case WHERE Id = :mockCase.Id];
for (Case c : cases) {
system.assertEquals(c.Decision__c, mockCase.Decision__c);
}
}
static testMethod void testRejectedReturnRefundCase() {
Case mockCase = new Case();
mockCase.Type = 'Request Return';
insert mockCase;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new HttpCalloutSuccessTest());
mockCase.Decision__c = 'Rejected';
update mockCase;
Test.stopTest();
List<Case> cases = [SELECT Id, Decision__c FROM Case WHERE Id = :mockCase.Id];
for (Case c : cases) {
system.assertEquals(c.Decision__c, mockCase.Decision__c);
}
}
static testMethod void testCaseApprovedWithoutReturnOptions() {
try
{
Case mockCase = new Case();
mockCase.Type = 'Request Return';
insert mockCase;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new HttpCalloutSuccessTest());
mockCase.Decision__c = 'Approved';
mockCase.ReturnOptions__c = null;
update mockCase;
Test.stopTest();
} catch (Exception e) {
System.assert(e.getMessage().contains('Please select Return Options before saving'), 'message=' + e.getMessage());
}
}
static testMethod void testCaseUpdatedWithHttpError() {
try
{
Case mockCase = new Case();
mockCase.Type = 'Request Return';
insert mockCase;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new HttpCalloutErrorTest());
mockCase.Decision__c = 'Approved';
mockCase.ReturnOptions__c = 'FOC without Returned Items';
update mockCase;
Test.stopTest();
} catch (Exception e) {
System.assert(e.getMessage().contains('Error calling endpoint /salesforce-case-updated'), 'message=' + e.getMessage());
}
}
}
HttpCalloutSuccessTest
global class HttpCalloutSuccessTest 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;
}
}
HttpCalloutErrorTest
#isTest
global class HttpCalloutErrorTest implements HttpCalloutMock{
global HttpResponse respond(HTTPRequest req){
HttpResponse res = new HttpResponse();
res.setStatusCode(500);
return res;
}
}
When i run the test in sandbox by clicking "Run ALL Test" - i see that cove coverage is 92%. SO i made outbound set and tried to deploy to prod.
But in prod when i validated inbound change set it complained about code code coverage issue.
Not sure what i'm doing wrong? If test cases are missing then for which part of the code?
So tests passed, no exceptions, "just" code coverage problem? You included the tests in the changeset?
This looks like it's supposed to be called from a Flow/ProcessBuilder (InvocableMethod). Did you include that flow in package? Is it active? Or Case trigger (if it's called from trigger)
Or make the unit test call HandleUpdateOnReturnRefundCase.handleUpdateOnReturnRefundCase() directly, without "firing mechanism". It's an unit test, not a whole system integration. Test blocks independently and composition separately, will help you nail any errors.
If you still can't figure it out - refresh new sandbox, deploy to it (without unit test run) and continue working there, examine debug logs etc.
Related
This is my batch class. I am facing a problem in the test class.
So please give me some solution on it. How to write this condition into class or how to write a test class for this.
I have this batch class created:
public class processBatch implements database.Batchable<object>, Database.AllowsCallouts, Scheduable{
public string AccountURL;
public String ProcessURL;
Public String Key;
private class JsonUpsertResult
{
List<Database.Error> Error {get;set;}
string SFDCId{get;set;}
String visibleID{get;set;}
Boolean is Created {get;set;}
Boolean isSuccess {get;set;}
}
public ProcessBatch(){
SAP_Details__c SAP = SAP_Details__c. getOrgDefaults();
AccountURL =SAP.Account_API_URL__c;
ProcessURL =SAP.process_API_URL__c;
Key =SAP.API_Key__c;
system.debug('API:' + ProcessURL + '-' + Key);
}
public Iterable<Object> start (Database.BatchableContext BC) {
List<Object> results =new List <Object>();
http http = new http();
httpRequest request =new HttpRequest();
system.debug('API:' '+ ProcessURL+' -' + Key);
request.setEndpoint(ProcessURL);
request.setMethod('POST');
request.setHeader('Authorization', Key);
request.setHeader('Accept', '*/*');
request.setHeader ('content-type', 'application/json');
}';
request.setBody(filters);
HttpResponse response =http.send(request);
if(responce.getStatusCode() == 200){
SAPProcessJsonApex2 gt = {SAPProcessJSON2Apex2) JSON.deserialize(response.getBody(), SAPProcessJSON2Apex.class);
List<SAPProcessJson2Apex.Result> res =gt.result;
system.debug('Size of Result: ' + res.size());
results = res;
}
return results;
}
public void execute (Database. BatchableContext BC, List<object> scope){
List<JSON2Apex.Results) accountResults = new List<JSON2Apex.Results>;
List<Process__c> ProcessToUpsert = new List<Process__c> ();
List<Process_Agent__c> CollectivesToupsert = new List<Process_Agent__c> ();
List<Department__c> departmentToupdate = new List<Department__c> ();
List<JSON2Apex.Results) revisedAccRes = new List JSON2Apex.Results> ();
List<SAPprocessJSON2Apex2.Results res = (List<SAPprocessJSO2Apex2.Results>) scope();
List<SAPprocessJSON2Apex2.Results revisedRes = nen List<SAPprocessJSONApex2.Results> ();
for (SAPprocessJSON2Apex2.Results r: res) {
SAPprocessJSON2Apex2.Document doc = r. document: List<SAPprocessJSON2 Apex2. Companies) comp = doc.companies;
List<SAPprocessJSON2Apex2.Companies> comp = doc.companies;
List<String> processTypes = doc.processTypes;
Lisk<String> categories = doc.categories;
Process__c pr = new Process__c ();
pr.Visibleprocess_No__c = doc.processId;
pr.Visible_method__c = 'SAP';
pr.process_Description__c = doc.description;
pr.Amount__c = doc.Amount;
pr.Construction_Type__c = doc.constructionType;
if(doc.phase == 'First planning'){
pr.Division=='First planning!';
} else if(doc.phase == 'Quotation'){
pr.Division == 'Main Step Quotation;
} else if(doc.phase = 'Contract Get') {
pr. Division== ' Main Step Agricultural';
}
pr.process_Full Name = doc.title;
pr.Name = doc.title.left (80);
if (categories.size() > 0){
if(categories [0] == 'Factory' || categories [0] = 'Storage' ){
pr.Sector__c = 'Industrial';
}else if(categories [0] == 'Packaging/Storage') {
pr. Type_of_Sector_c = 'Warehouse';
}else if(categories[0] == 'Shops and Retail' || categories [0]=='Any Showrooms') {
pr.Sector__c = 'Commercial';
}
if(pr.Sector__c != null && doc.Amount >= 50000){
ProcessToUpsert.ada (p);
revisedRes.ada (r);
} } }
public void finish (Database.BatchableContext BC) {
}
public void execute (SchedulableContext sc) {
database.executeBatch (new ProcessBatch (), 30);
}
}
&& d.Amount__c>= 50000 Whenever I write this condition in my class then my test class covers only 35%, and when I remove this condition it covers 80%. This condition is correct according to the requirement.
Test Class
#isIest (SeeAllData = true)
public class ProcessBatchTest {
#isTest public static void processBatchTest () {
Test.setMock (HttpCalloutMock.class, new HttpMock());
ProcessBatch pb = new ProcessBatch();
Test.startTest();
database.executeBatch (pb,30);
Test.stopTest();
You control the HttpMock class that pretends it returns results from SAP callout in the test. Nothing stops you from going there and making it return 2 records (1 with amount below 50K, 1 with amount above), or multiple statuses or whatever else you need.
I try to get bad request error using below .json,But I am not getting .I want send this response.
For example:
validation errors:
{
"StatusCode":"400",
"id":"",
"error":"xxxx"
}
2.Internal Server error:
{
"StatusCode":"500",
"id":"",
"error":"xxxx"
}
Apex REST API class :
#RestResource(urlMapping='/IoT_Case__c/*')
global with sharing class IOT_CaseManager {
global class ResponseWrapper{
public String StatusCode;
public String StatusMessage;
public String ErrorMessage;
public String ID;
//public List<IoT_Case__c> Details;
}
#HttpPost
global static ResponseWrapper createIOT_Case(String IOT_Case_Type,
String Name,String Email,String Phone,String Facility_Name,
String Address,String case_Reason,string Device_ID,
String Date_time, String Pool_Name){
RestRequest request = RestContext.request;
ResponseWrapper resp = new ResponseWrapper();
system.debug('%%%%%% the response is######'+resp);
List<IoT_Case__c> caseList = new List< IoT_Case__c> ();
try{
IoT_Case__c Iot_case = new IoT_Case__c ();
Iot_case.IOT_Case_Type__c=IOT_Case_Type;
Iot_case.Name__c= Name;
Iot_case.Email__c= Email;
Iot_case.Phone__c= Phone;
Iot_case.Address__c= Address;
Iot_case.Pool_Name__c= Pool_Name;
Iot_case.Device_ID__c= Device_ID;
Iot_case.case_Reason__c=case_Reason;
Iot_case.Facility_Name__c=Facility_Name;
Iot_case.Date_time__c=Date.valueOf(Date_time);
caseList.add(Iot_case);
if (caseList.size() > 0){
List<IoT_Case__c> Iotcase_List = [SELECT ID,Name__c,case_Reason__c,Device_ID__c,IOT_Case_status__c from IoT_Case__c];
// system.debug('####the value is &&&&&'+ Iotcase_List);
For (Iot_case__c ic:Iotcase_List){
if ((ic.IOT_Case_status__c == 'Open'|| ic.IOT_Case_status__c == 'In -Progress') && (ic.case_Reason__c == caseList[0].case_Reason__c && ic.Device_ID__c == caseList[0].Device_ID__c)){
resp.errorMessage='Duplicate case';
system.debug('####the value is &&&&&'+resp.errorMessage );
}
}
if(resp.errorMessage!='Duplicate case'){
insert caseList;
resp.statusCode ='201';
resp.statusMessage ='Success' ;
}
else{
resp.statusCode ='409';
resp.statusMessage ='Duplicate' ;
}
}
}
catch (Exception e) {
system.debug('&&&&&&& The errro message is *****'+ e);
if(e.getMessage().contains('Validation'))
{
resp.statusCode = '400';
resp.statusMessage = 'Exception : ' + e.getMessage();
}
if(e.getMessage().contains('Internal server error '))
{
resp.statusCode = '500';
resp.statusMessage = 'Exception : ' + e.getMessage();
}
}
string Outputget= JSON.serialize((caseList));
//resp.Details = caseList;
resp.ID = caseList[0].Id;
system.debug('######the response id is&&&&&'+resp.ID );
//resp.ErrorMessage= 'Exception ' ;
return resp;
}
}
json :
{
"IOT_Case_Type": "Equipment_Replacement",
"Name": "test123",
"Email": "test1#gmail.com",
"Phone": "9086978010",
"Address": "Chennai",
"Pool_Name": "Pool-1",
"Facility_Name": "Facility-1",
"Device_ID" : "D1110" ,
"case_Reason" : "FAC Sensor Expired,ORP Sensor Expired,pH Sensor Expired",
"Date_time": "2021-02-01T03:42:22Z"
}
endpoint Post url :/services/apexrest/IoT_Case__c/*
if(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'))
{
resp.statusCode = '400';
resp.statusMessage = 'Exception : ' + e.getMessage();
resp.ErrorMessage= 'Bad Request Exception' ;
}
else{
resp.statusCode = '500';
resp.statusMessage = 'Exception :' + e.getMessage();
resp.ErrorMessage= 'Internal server Exception ' ;
}
I need test class with 80% code coverage for above class .
I tried this but i am getting 58% code coverage only .
#isTest
Public class IOT_CaseManagerTest{
static testMethod void testDoPost(){
IoT_Case__c Iot_case = new IoT_Case__c();
Iot_case.IOT_Case_Type__c='Equipment_Replacement';
Iot_case.Name__c='';
Iot_case.Email__c='test1#gmail.com';
Iot_case.Phone__c='9573678567';
Iot_case.Address__c='Chennai';
Iot_case.Pool_Name__c='Pool-1';
Iot_case.Device_ID__c='CAS968878';
Iot_case.case_Reason__c='FAC Sensor Expired,ORP Sensor Expired,pH Sensor Expired';
Iot_case.Facility_Name__c='Facility-1';
Iot_case.Date_time__c=system.Today();
insert Iot_case;
Test.startTest();
IOT_CaseManager.createIOT_Case('Equipment_Replacement','sreenitest','test1#gmail.com','9573678567','Chennai','Pool-1','CAS968878','FAC Sensor Expired','Facility-1','8/25/2021');
Test.stopTest();
}
static testMethod void testPostMethod()
{
RestRequest request = new RestRequest();
request.requestUri ='/services/apexrest/IoT_Case__c/*';
request.httpMethod = 'POST';
RestContext.request = request;
IOT_CaseManager.createIOT_Case('Equipment_Replacement','sreenitest','test1#gmail.com','9997877','Chennai-2','Pool-1','CAS968898','FAC Sensor Expired','Facility-1','8/25/2021');
//System.assert(strId !=null );
}
}
I have a class where in I am trying to call a HTTP request. I have created a Mock Test and a Test class.
My Test class is successful with 28% code coverage but it fails in recognizing the call out methods I have used in my class Below is code
My Class -
public class PD_WelcomeMaroPost {
#future(callout=true)
public static void sendEmailThroughMaro(string myInpEmail) {
string successContacts = '';
string failureContacts = '';
List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
//List<Case> newCase = new List<Case>();
// SQL to fetch FBO who Joined Today
list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
(SELECT Id FROM Stripe_Subscriptons__r WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false LIMIT 1)from account
where ID IN (select Distributor__c from Stripe_Subscripton__c
where Start_Date__c= TODAY AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL LIMIT 100]);
system.debug('>>>>>>>>>>' + conts);
overallEmail myEmail = new overallEmail();
for(Account c : conts){
string resultBodyGet = '';
myEmail.email.campaign_id = 172;
myEmail.email.contact.Email = c.Email_FLP_com__c;
myEmail.email.contact.first_name = c.name;
/**MAp<String, String> tags = new Map<String, String>();
tags.put('firstName', c.name);
myEmail.email.tags = tags;**/
system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
try{
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Http http = new Http();
system.debug('Sending email');
HTTPResponse response = http.send(req);
system.debug('sent email');
resultBodyGet = response.getBody();
system.debug('Output response:' + resultBodyGet);
maroResponse myMaroResponse = new maroResponse();
myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
system.debug('#### myMaroResponse: ' + myMaroResponse);
if(myMaroResponse.message == 'Email was sent successfully')
successContacts = successContacts + ';' + c.Email_FLP_com__c;
else
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
}
catch (exception e) {
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
system.debug('#### Exception caught: ' + e.getMessage());
}
c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
}
Update subsToUpdate;
}
public class maroResponse {
public string message {get;set;}
}
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
//Public Map<String, String> tags;
}
public class contactJson {
public string email;
public string first_name;
}
}
My MockTest Class- I have used this Mockclass to generate Mock response. The documentation does not have a test method thus used the same format
#isTest
Global class PD_WelcomeMaroPostMock implements HttpCalloutMock {
Global HttpResponse respond(HttpRequest req) {
// Create a fake response
//
//System.assertEquals(JSON.serialize(myEmail),req.getbody());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
This is my Test class - This is the class I have used for the response. I have a successful insert job but my HTTP responses are failing.
#IsTest
private class PD_WelcomeMaroPost_test {
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
}
public class contactJson {
public string email;
public string first_name;
}
#IsTest
private static void testemail() {
overallEmail myEmail = new overallEmail();
Account a = new Account();
a.Name ='Test' ;
a.Email_FLP_com__c = 'test#nextsphere.com';
insert a ;
Stripe_Subscripton__c s = new Stripe_Subscripton__c();
// insert subscription --
s.Distributor__c = a.Id;
S.Welcome_Email__c = TRUE;
S.Welcome_Email_Sent_Date__c = system.today();
s.Subscription_Id__c = 'sub_9H0LLYFZkekdMA' ;
INSERT S;
Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Test.startTest();
PD_WelcomeMaroPost.sendEmailThroughMaro('test#nextsphere.com');
Test.stopTest();
}
}
When declaring a Mock myself, I declare it inside the test start transaction:
Test.startTest();
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Rest of test code here
Test.stopTest();
Also inside your test class you seem to only build the HTTP request and not send it try adding the below:
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) { } else { }
I am using Play 2.0.4 and I'm doing a test unit for actors who make use of the database.
The test begins well, but then at a given moment the connection with the database is closed and the actor who is running fails.
Code:
public class ActorTest extends Helpers {
private FakeApplication app;
private ActorSystem actorSystem;
private ActorRef actorRef;
private BankAccount account;
#Before
public void initTest() {
Map<String, String> params = new HashMap<String, String>();
params.put("db.default.driver", "com.mysql.jdbc.Driver");
params.put("db.default.url", "mysql://root:XXXX#localhost/YYY");
params.put("ebean.default", "models.*");
app = fakeApplication(params);
actorSystem = play.api.libs.concurrent.Akka.system(app.getWrappedApplication());
}
#Test
public void updateAccountTransaction() {
running(app, new Runnable() {
#Override
public void run() {
account = BankAccount.find.byId(new Long(1));
actorRef = actorSystem.actorOf(new Props(new UntypedActorFactory() {
#Override
public UntypedActor create() {
return new AccountTaskActor(account);
}
}));
Calendar fromDate = Calendar.getInstance();
....
....
Calendar toDate = Calendar.getInstance();
final InputRangeDateMessage param = new InputRangeDateMessage(fromDate, toDate);
junit.framework.Assert.assertNotNull(account);
Future<Object> future = Patterns.ask(actorRef, param, 1000000);
Promise<Object> sdf = Akka.asPromise(future);
Promise<Result> r2 = sdf.map(new Function<Object, Result>() {
#Override
public Result apply(Object response) throws Throwable {
if (response instanceof ErrorMessage) {
ErrorMessage e = (ErrorMessage) response;
System.out.println("Error Message " + e.getErrorText());
junit.framework.Assert.assertEquals(e.getErrorCode(), -1);
} else if (response instanceof BankAccountMessage) {
BankAccount a = ((BankAccountMessage) response).getAccount();
System.out.println("BankAccount " + a.accountsLastUpdate);
}
return ok();
}
});
Result test2;
test2 = async(r2);
}
});
}
}
AFAIK, you have to wait for the end of your Promise:
...
Result test2 = r2.get();
I have following class to send email
global class SendConfirmation {
public SendConfirmation(ApexPages.StandardController controller)
{
}
Webservice static void SendEmail(string contactId,string oppId)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(contactId);
mail.setWhatId(oppId);
mail.setTemplateId('00Xd0000000PFaY');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
ablove class is fine
but not able to get following test case to complete code coverage in eclipse
#isTest
private class SendConfirmationTestCase {
private static testMethod void myUnitTest() {
Contact con = new Contact();
con.FirstName = 'Anil';
con.LastName = 'Dutt';
con.Email = 'anil#swiftsetup.com';
insert con;
Opportunity oppNew = new Opportunity();
oppNew.Name = 'Test Opp';
oppNew.StageName = 'Ticketing';
oppNew.CloseDate = System.now().date();
insert oppNew;
//ApexPages.StandardController sc = new ApexPages.StandardController(con);
//SendConfirmation sc1=new SendConfirmation (sc);
//sc1.SendEmail();
}
}
If i comment out last 3 lines from test case
Following error is coming
SendConfirmationTestCase: Invalid type: SendConfirmation
Thanks in advance for your help..
Try this, it's testing at 100% for me.
global class SendConfirmation
{
public SendConfirmation(ApexPages.StandardController controller)
{
}
Webservice static void SendEmail(string contactId,string oppId)
{
Messaging.SingleEmailMessage mail
= new Messaging.SingleEmailMessage();
mail.setTargetObjectId(contactId);
mail.setWhatId(oppId);
// assuming this Template ID exists in your org
mail.setTemplateId('00Xd0000000PFaY');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
private static testMethod void myUnitTest()
{
Contact con = new Contact();
con.FirstName = 'Anil';
con.LastName = 'Dutt';
con.Email = 'anil#swiftsetup.com';
insert con;
Opportunity oppNew = new Opportunity();
oppNew.Name = 'Test Opp';
oppNew.StageName = 'Ticketing';
oppNew.CloseDate = System.now().date();
insert oppNew;
ApexPages.StandardController sc
= new ApexPages.StandardController(con);
SendConfirmation sc1=new SendConfirmation (sc); // test constructor
// Not: sc1.SendEmail();
// Because method is a webservice in a global class
SendConfirmation.SendEmail(con.Id,oppNew.Id);
}
}