Salesforce Apex unit testing error - unit-testing

I am trying to create a Salesforce unit test for a new trigger I created.
trigger SOSCreateCaseCustom on SOSSession (before insert) {
List<Event> aplist = new List<Event>();
List<SOSSession> sosSess = Trigger.new;
for (SOSSession s : sosSess) {
try {
Case caseToAdd = new Case();
caseToAdd.Subject = 'SOS Video Chat';
if (s.ContactId != null) {
caseToAdd.ContactId = s.ContactId;
} else {
List<Contact> contactInfo = [SELECT Id from Contact WHERE Email = :s.AppVersion];
if (!contactInfo.isEmpty()) {
caseToAdd.ContactId = contactInfo[0].Id;
s.ContactId = contactInfo[0].Id;
}
}
insert caseToAdd; s.CaseId = caseToAdd.Id;
}catch(Exception e){}
}
}
Here is my unit test:
#isTest
private class SOSCreateCaseCustomTest {
static testMethod void validateSOSCreateCase() {
String caseSubject = 'SOS Video Chat';
// set up case to add
SOSSession s = new SOSSession();
insert s;
Case caseToAdd = new Case(Subject='SOS Video Chat');
caseToAdd.ContactId = s.ContactId;
insert caseToAdd;
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
// Test that escaltion trigger correctly escalate the question to a case
System.assertEquals(s.ContactId, ca.ContactId);
}
}
I keep getting this error.
System.QueryException: List has more than 1 row for assignment to SObject
I am new to Apex and I have no idea how to fix this. Any Salesforce and Apex experts out there who can help? Thanks!

I think this one:
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
Because the casSubject may query more then one Case.... You should use List

The following line is causing issue :
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
It is returning two cases, the one you inserted in test data and other that is inserted by trigger. So it is having two records for Subject 'SOS Video Chat';
If you change the Subject from 'SOS Video Chat' to any other String it will run successfully.

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);
}

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.

Unit Test for Apex Trigger that Concatenates Fields

I am trying to write a test for a before trigger that takes fields from a custom object and concatenates them into a custom Key__c field.
The trigger works in the Sandbox and now I am trying to get it into production. However, whenever I try and do a System.assert/assertEquals after I create a purchase and perform DML, the value of Key__c always returns null. I am aware I can create a flow/process to do this, but I am trying to solve this with code for my own edification. How can I get the fields to concatenate and return properly in the test? (the commented out asserts are what I have tried so far, and have failed when run)
trigger Composite_Key on Purchases__c (before insert, before update) {
if(Trigger.isBefore)
{
for(Purchases__c purchase : trigger.new)
{
String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
}
}
}
#isTest
public class CompositeKeyTest {
public static testMethod void testPurchase() {
//create a purchase to fire the trigger
Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1.0,number_of_seats__c='test',add_datetime__c='test');
Insert purchase;
//System.assert(purchases__c.Key__c.getDescribe().getName() == 'testesttest1testtest');
//System.assertEquals('testtesttest1.0testtest',purchase.Key__c);
}
static testMethod void testbulkPurchase(){
List<Purchases__c> purchaseList = new List<Purchases__c>();
for(integer i=0 ; i < 10; i++)
{
Purchases__c purchaserec = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c= i+1.0 ,number_of_seats__c='test',add_datetime__c='test');
purchaseList.add(purchaserec);
}
insert purchaseList;
//System.assertEquals('testtesttest5testtest',purchaseList[4].Key__c,'Key is not Valid');
}
}
You need to requery the records after inserting them to get the updated data from the triggers/database

Writing a test class on a Trigger in Salesforce

I am a complete code noob and need help writing a test class for a trigger in Salesforce. Any help would be greatly appreciated.
Here is the trigger:
trigger UpdateWonAccounts on Opportunity(before Update) {
Set < Id > accountIds = new Set < Id > ();
//Collect End user Ids which has won Opportunities
for (Opportunity o : Trigger.new) {
if (o.isWon && o.EndUserAccountName__c != null) {
accountIds.add(o.EndUserAccountName__c);
}
}
List < Account > lstAccount = new List < Account > ();
//Iterate and collect all the end user records
for (Account a : [Select Id, Status__c From Account where Id IN : accountIds]) {
lstAccount.add(new Account(Id = a.Id, Status__c = true));
}
//If there are any accounts then update the records
if (!lstAccount.isEmpty()) {
update lstAccount;
}
}
Read An Introduction to Apex Code Test Methods and How To Write A Trigger Test.
Basically, you want to create a new testmethod that updates (inserts, deletes, undeletes, etc. depending on your trigger conditions) a record or sObject.
It looks somewhat like this:
public class myClass {
static testMethod void myTest() {
// Add test method logic to insert and update a new Opportunity here
}
}

subsonic 3.0 active record update

I am able to retrieve database values and insert database values, but I can't figure out what the Update() syntax should be with a where statement.
Environment -> ASP.Net, C#
Settings.ttinclude
const string Namespace = "subsonic_db.Data";
const string ConnectionStringName = "subsonic_dbConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "subsonic_db";
Retreive example
var product = equipment.SingleOrDefault(x => x.id == 1);
Insert Example
equipment my_equipment = new equipment();
try
{
// insert
my_equipment.parent_id = 0;
my_equipment.primary_id = 0;
my_equipment.product_code = product_code.Text;
my_equipment.product_description = product_description.Text;
my_equipment.product_type_id = Convert.ToInt32(product_type_id.SelectedItem.Value);
my_equipment.created_date = DateTime.Now;
my_equipment.serial_number = serial_number.Text;
my_equipment.Save();
}
catch (Exception err)
{
lblError.Text = err.Message;
}
Edit: Think that I was just too tired last night, it is pretty easy to update. Just use the retrieve function and use the Update() on that.
var equip = Equipment.SingleOrDefault(x => x.id == 1);
lblGeneral.Text = equip.product_description;
equip.product_description = "Test";
equip.Update();
Resolved. View answer above.