what is wrong with my test class in apex force.com code? - salesforce

I have written a working class in Apex. It is an Email service extender, that processes incoming emails.
It is working perfect on my sandbox enviroment.
I have created a test class, so I can also deploy it to my production, but when validating the code, I get the only 72% of my code is tested.
This is my main class
global class inboundEmail implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
Lead lead;
String [] mFromUserParams;
String [] sourceText;
String mCaseObject;
try{
sourceText = email.toAddresses[0].split('#');
String [] mParams = sourceText[0].split('\\.');
**// FROM THIS LINE TO THE END - NOT COVERED**
mFromUserParams = email.fromAddress.split('#');
mCaseObject = mParams[0];
if (mCaseObject == 'lead'){
lead = new Lead();
lead.LastName = mFromUserParams[0];
lead.Company = email.fromAddress;
lead.OwnerId = mParams[1];
lead.LeadSource = mParams[2];
lead.Email = email.fromAddress;
lead.RequirementsDescription__c = email.subject + email.plainTextBody;
insert lead;
result.success = true;
} else if (mCaseObject == 'case'){
result.success = true;
} else {
result.success = false;
}
}catch(Exception e){
result.success = false;
result.message = 'Oops, I failed.';
}
return result;
}
}
This is my test class
#isTest
private class inboundEmailTest {
public static testMethod void inboundEmail(){
// Create a new email, envelope object and Header
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
envelope.toAddress = 'lead.owner.new#cpeneac.cl.apex.sandbox.salesforce.com';
envelope.fromAddress = 'user#acme.com';
email.subject = 'Please contact me';
email.fromName = 'Test From Name';
email.plainTextBody = 'Hello, this a test email body. for testing Bye';
// setup controller object
inboundEmail catcher = new inboundEmail();
Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
}
}
According to the error message, ALL lines in the Try/Catch block from the 3rd line are not covered. (marked in the code).

in your test method you're setting envelope.toAddress but in your email service you're splitting the first element of the actual InboundEmail objects toAddresses. this probably causes either an ArrayIndexOutOfBoundsException or a NPE because the element 0 does not exist. so the code coverage will be poor because your test always jumps into the exception handling and leaves the rest of you code uncovered. just set the emails toAddresses and you should have a better coverage.
h9nry

In your test code, can you add a scenario that causes the lead insert to fail? This will cause the code in your catch block to execute and provide you the needed code test coverage.

The email.fromAddress is not a list by default, so just setting that to a string and not a list solved this.

Related

An unexpected null key in HashSet, the first be added not the rest

I'm learning Activiti 7, I drew a BPMN diagram as below:
When the highlight1 UserTask has been completed but the highlight2 UserTask is still pending, I ran the following code to highlight the completed flow element.
private AjaxResponse highlightHistoricProcess(#RequestParam("instanceId") String instanceId,
#AuthenticationPrincipal UserInfo userInfo) {
try {
// Get the instance from the history table
HistoricProcessInstance instance = historyService
.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId());
Process process = bpmnModel.getProcesses().get(0);
// Get all process elements, including sequences, events, activities, etc.
Collection<FlowElement> flowElements = process.getFlowElements();
Map<String, String> sequenceFlowMap = Maps.newHashMap();
flowElements.forEach(e -> {
if (e instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) e;
String sourceRef = sequenceFlow.getSourceRef();
String targetRef = sequenceFlow.getTargetRef();
sequenceFlowMap.put(sourceRef + targetRef, sequenceFlow.getId());
}
});
// Get all historical Activities, i.e. those that have been executed and those that are currently being executed
List<HistoricActivityInstance> actList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.list();
// Each history Activity is combined two by two
Set<String> actPairSet = new HashSet<>();
for (HistoricActivityInstance actA : actList) {
for (HistoricActivityInstance actB : actList) {
if (actA != actB) {
actPairSet.add(actA.getActivityId() + actB.getActivityId());
}
}
}
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
// Get the completed Activity
List<HistoricActivityInstance> finishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.finished()
.list();
// Highlight the completed Activity
Set<String> highActSet = Sets.newHashSet();
finishedActList.forEach(point -> highActSet.add(point.getActivityId()));
// Get the pending highlighted node, i.e. the currently executing node
List<HistoricActivityInstance> unfinishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.unfinished()
.list();
Set<String> unfinishedPointSet = Sets.newHashSet();
unfinishedActList.forEach(point -> unfinishedPointSet.add(point.getActivityId()));
...
return AjaxResponse.ajax(ResponseCode.SUCCESS.getCode(),
ResponseCode.SUCCESS.getDesc(),
null);
} catch (Exception e) {
e.printStackTrace();
return AjaxResponse.ajax(ResponseCode.ERROR.getCode(),
"highlight failure",
e.toString());
}
}
Please see this piece of code:
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
It was expected to get 2 elements in the highSequenceSet, but it got 3, with a unexpected null.
The log printed in the console was:
Why is the first null added to the HashSet but not the rest?
Why is the first null added to the HashSet but not the rest?
HashSet implements the Set interface, duplicate values are not allowed.

How to make a correct select query on google endpoint?

I created an Android project using Google Cloud Endpoints, I created a model class Poll.java and now I want to make a query in the PollEndpoint.java class, to retrieve a poll with a specific author.
This is the query code in PollEndpoint.java
#ApiMethod(name = "getSpecificPoll", path="lastpoll")
public Poll getSpecificPoll(#Named("creator") String creator) {
EntityManager mgr = getEntityManager();
Poll specificPoll = null;
try {
Query query = mgr.createQuery("select from Poll where creator
='"+creator+"'");
specificPoll = (Poll) query.getSingleResult();
} finally {
mgr.close();
}
return specificPoll;
}
The code in the client part is:
private class PollQuery extends AsyncTask<Void, Void, Poll> {
#Override
protected Poll doInBackground(Void... params) {
Poll pollQuery = new Poll();
Pollendpoint.Builder builderQuery = new Pollendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new
JacksonFactory(),null);
builderQuery = CloudEndpointUtils.updateBuilder(builderQuery);
Pollendpoint endpointQuery = builderQuery.build();
try {
pollQuery =
endpointQuery.getSpecificPoll("Bill").execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (pollQuery != null){
System.out.println(pollQuery.getKeyPoll().getId());
} else System.out.println("Null query");
return null;
}
The problem is that the server throw an exception:
javax.persistence.PersistenceException: FROM clause of query has class com.development.pollmeproject.Poll but no alias
at org.datanucleus.api.jpa.NucleusJPAHelper.getJPAExceptionForNucleusException(NucleusJPAHelper.java:302)
I think that the query statement is not correct, how can I write a correct one?
The query you provided is NOT valid JPQL. JPQL is more of the form
SELECT p FROM Poll p WHERE p.creator = :creatorParam
The error message does tell you that though, so I'm not sure why you're not sure of it

OptionSetValue does not contain constructor which takes one argument

I am creating a silverlight application as a web resource for CRM 2011. Now i am creating a ServiceAppointment record in DB and after creating it i want to change its Status to "reserved" instead of requested.
I googled about this and come across the examples like Close a Service Activity Through Code and Microsoft.Crm.Sdk.Messages.SetStateRequest
They all suggesting to use "SetStateRequest" and for using this i have to set the OptionSetValue like
request["State"] = new OptionSetValue(4);
But above line gives me error saying "OptionSetValue does not contain constructor which takes one argument"
BTW i am using SOAP end point of CRM 2011 service in silverlight application
Any ideas friends?
EDIT
Following is my code
var request = new OrganizationRequest { RequestName = "SetStateRequest" };
request["State"] = 3;
request["Status"] = 4;
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
And my callback function is
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}
You must some how be referencing some other OptionSetValue class that is not the Microsoft.Xrm.Sdk one. Try appending the namespace to see if that resolves your issue:
request["State"] = new Microsoft.Xrm.Sdk.OptionSetValue(4);
Also, why are you using late bound on the SetStateRequest? Just use the SetStateRequest class:
public static Microsoft.Crm.Sdk.Messages.SetStateResponse SetState(this IOrganizationService service,
Entity entity, int state, int? status)
{
var setStateReq = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
setStateReq.EntityMoniker = entity.ToEntityReference();
setStateReq.State = new OptionSetValue(state);
setStateReq.Status = new OptionSetValue(status ?? -1);
return (Microsoft.Crm.Sdk.Messages.SetStateResponse)service.Execute(setStateReq);
}
Thanks Daryl for you time and effort. I have solved my problem with the way u have suggested.
I am posting my code that worked for me.
var request = new OrganizationRequest { RequestName = "SetState" };
request["State"] = new OptionSetValue { Value = 3 };
request["Status"] = new OptionSetValue { Value = 4 };
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}

context.SaveChanges() not persisting data in database

Im working on a MVC app.
When I call context.SaveChanges to update a specific records. The update is not registered in the database. I do not get any runtime error either. All in notice is that my Records is not updated. I still see the same values. Insert Functionality work Perfectly.
enter code here
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
VDData.Student_Master studentmaster = new VDData.Student_Master();
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges(); // here it wont give any kind of error. it runs sucessfully. }
First get the entity you are going to update:
var entity = obj.GetEntity(id);
entity.col1 = "value";
context.SaveChanges(entity);
hope this will help.
It seems like you want to update, so your code should be
VDData.Student_Master studentmaster = context.Student_Masters.Single(p=>p.Student_ID == stuid);
And you should not change the Student_ID if it is the primary key.
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
//VDData.Student_Master studentmaster = new VDData.Student_Master();
//REPLACE WITH
VDData.Student_Master studentmaster = context.Student_Masters.Where(p=>p.Student_ID == stuid);
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges();
Before
context.SaveChanges();
You need to call this
context.Student_Masters.Add(studentmaster );
Edit: introduce Abstraction to your Context class and Create a method in your context class like below, then you can call it whenever you want to create or update your objects.
public void SaveStudent_Master(Student_Master studentmaster)
{
using (var context = new VDData.VidyaDaanEntities())
{
if (studentmaster.Student_ID == 0)
{
context.Student_Masters.Add(studentmaster);
}
else if (studentmaster.Student_ID > 0)
{
//This Updates N-Level deep Object grapgh
//This is important for Updates
var currentStudent_Master = context.Student_Masters
.Single(s => s.Student_ID == studentmaster.Student_ID );
context.Entry(currentStudent_Master ).CurrentValues.SetValues(studentmaster);
}
context.SaveChanges();
}
Then in your Controller replace context.SaveChanges(); with _context.SaveStudent_Master(studentmaster);

Strange error message when using SaveChanges in EF with MVC

I have a dropdownlistfor with values that is not from my database, and when a user select values that does not exist in my database, I want to save it to the database(and if it already exist, I just use the existing data).
This work fine with some of my data(see code for where it does not work)
This is my repository:
public void newPerson(Person addperson)
{
db.Person.AddObject(addperson);
db.SaveChanges(); //This wont work
}
here is my controller:
[HttpPost]
public ActionResult Create(CreateNKIphase1ViewModel model)
{
if (ModelState.IsValid)
{
var goalcard = new GoalCard();
var companyChecker = "";
var dbCompanies = createNKIRep.GetCustomerByName();
var addcustomer = new Customer();
foreach (var existingcustomer in dbCompanies)
{
companyChecker = existingcustomer.CompanyName;
if (existingcustomer.CompanyName == model.CompanyName)
{
var customerId = existingcustomer.Id;
var selectedCustomerID = createNKIRep.GetByCustomerID(customerId);
goalcard.Customer = selectedCustomerID;
break;
}
}
if (companyChecker != model.CompanyName)
{
addcustomer.CompanyName = model.CompanyName;
createNKIRep.newCustomer(addcustomer); //This works!
goalcard.Customer = addcustomer;
}
if (model.PersonName != null)
{
var Personchecker = "";
var dbPersons = createNKIRep.GetPersonsByName();
foreach (var existingPerson in dbPersons)
{
Personchecker = existingPerson.Name;
if (existingPerson.Name == model.PersonName)
{
var personId = existingPerson.Id;
var selectedPersonID = createNKIRep.GetByPersonID(personId);
goalcard.Person = selectedPersonID;
break;
}
}
if (Personchecker != model.PersonName)
{
Person newPerson = new Person();
newPerson.Name = model.PersonName;
createNKIRep.newPerson(newPerson);//Where repository is called
goalcard.Person = newPerson;
}
}
But when I try to save a new Person I get the following error message:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Even though Person only have Id and name as attributes in my database.
Is there anything wrong in my code, or is it any setting in my database that has to be changed?
Thanks in advance.
It's because I use db.SaveChanges(); multiple times in one post. Reducing numbers of time I use db.SaveChanges helped me get rid of the error.

Resources