Writing Test class for Currency Conversion Trigger - triggers

I need little assistance in writing a test class for this trigger that converts the record currency to org currency. Can anyone please assist/guide? Please.
trigger convertToEuro on CustomObject(before update) {
List<CurrencyType> currencyTypeList = [select id,IsoCode,ConversionRate from CurrencyType where isActive = true] ;
Map<String , Decimal> isoWithRateMap = new Map<String, Decimal>();
for(CurrencyType c : currencyTypeList) {
isoWithRateMap.put(c.IsoCode , c.ConversionRate) ;
}
for(CustomObject ce: trigger.new){
if(ce.CurrencyIsoCode != 'EUR' && isoWithRateMap.containsKey(ce.CurrencyIsoCode)){
ce.Amount_Converted__c = ce.ffps_iv__Amount__c/ isoWithRateMap.get(ce.CurrencyIsoCode);
}
}
}

#isTest(seealldata=false)
public class testConvertToEuro{
#testSetup
static void setupTest(){
List<CurrencyType> liCT = New List<CurrencyType>();
List<CustomObject> liCO = New List<CustomObject>();
Integer iCounter = 0;
liCT.add(new CurrencyType(IsoCode='EUR',ConversionRate=1,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='USD',ConversionRate=2,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='XXX',ConversionRate=3,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='YYY',ConversionRate=4,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='ZZZ',ConversionRate=5,isActive=TRUE));
for(Integer i=0; i<251; i++){
CustomObject co = New CustomObject(
CurrencyIsoCode = liCT[iCounter].IsoCode;
ffps_iv__Amount__c = liCT[iCounter].ConversionRate + .01;
);
if(iCounter < liCT.size() -1){
iCounter += 1;
}
else{
iCounter = 0;
}
}
insert liCT;
insert liCO;
}
static testmethod void runTest(){
setupTest();
List<CustomObject> liCustomObjectsToUpdate = New List<CustomObject>();
for(CustomObject co : [SELECT Id, ffps_iv__Amount__c, Amount_Converted__c from CustomObject]){
co.ffps_iv__Amount__c -= .01;
liCustomObjectsToUpdate.add(co);
}
test.startTest();
Update liCustomObjectsToUpdate;
test.stopTest();
System.assertEquals([SELECT Id, Amount_Converted__c FROM CustomObject LIMIT 1][0].Amount_Converted__c, 1);
}
}
I can't test this code without adding your custom object so it might have some errors. Please let me know what errors you are getting. If you want help debugging, you should provide the exact code being used and the exact error message.
It follows the basic pattern for testing update triggers:
Insert test data
Retrieve test data
Update records
Assert that the trigger generated the desired result

Related

Dynamics CRM plugin -Pre Operation Update

I created a plug-in that calculates the pricing of the quote based on custom fields whenever update done on the quote entity.I executed the plugin on pre-opertaion update of the quote entity.I tried to debbug my plugin, it retrives null values.For example the value of the field "edm_CashAmount" contains 5000 but the code retrieved null. Kindly advise on the below. Thanks in advance.
namespace CRMPlugins.Plugins
{
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk.Messages;
public class PrequoteUpdate : Plugin
{
public PrequoteUpdate()
: base(typeof(PrequoteUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "quote", new Action<LocalPluginContext>(ExecutePrequoteUpdate)));
}
protected void ExecutePrequoteUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
Entity entity = null;
if (localContext.PluginExecutionContext.InputParameters.Contains("Target") && localContext.PluginExecutionContext.InputParameters["Target"] is Entity)
{
entity = (Entity)localContext.PluginExecutionContext.InputParameters["Target"];
}
else
{
return;
}
decimal instotal = 0;
Quote quote = entity.ToEntity<Quote>();
using (GeneratedEntities orgContext = new GeneratedEntities(localContext.OrganizationService))
{
var installements = (from b in orgContext.edm_installementSet
where b.GetAttributeValue<Guid>("edm_quote") == quote.QuoteId
select b);
foreach (var c in installements)
{
if (c.edm_Amount != null)
{
instotal += (decimal)c.new_Decimal;
}
}
}
decimal cash = 0;
if (quote.edm_CashAmount != null)
{
cash = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_cashamount").Value);
}
decimal check = 0;
if (quote.edm_CheckAmount != null)
{
check = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_checkamount").Value);
}
decimal credit = 0;
if (quote.edm_CreditCardAmount != null)
{
credit = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_creditcardamount").Value);
}
decimal gift = 0;
if (quote.new_GiftCard != null)
{
gift = Convert.ToDecimal(quote.GetAttributeValue<Money>("new_giftcard").Value);
}
decimal total = 0;
if (quote.TotalLineItemAmount != null)
{
total = Convert.ToDecimal(quote.GetAttributeValue<Money>("totallineitemamount").Value);
}
decimal currentbalane = 0;
if (quote.edm_CurrentBalane != null)
{
currentbalane = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_currentbalane").Value);
}
decimal DiscAmount = 0;
if (quote.DiscountAmount != null)
{
DiscAmount = Convert.ToDecimal(quote.GetAttributeValue<Money>("discountamount").Value);
}
decimal totalafterdiscount = total - DiscAmount;
decimal tax = (totalafterdiscount * 10) / 100;
decimal totalwithvat = totalafterdiscount + tax;
decimal paidamount = cash + check + credit + gift + instotal;
decimal remainingamount = totalwithvat - paidamount;
quote["edm_cashamount_1"] = new Money(tax);
quote["edm_totaltax"] = new Money(tax);
quote["edm_paidamount"] = new Money(paidamount);
quote["edm_remainingamount"] = new Money(remainingamount);
quote["edm_total"] = new Money(totalwithvat);
quote["edm_totalinstallements"] = new Money(instotal);
quote["edm_checkamount_1"] = new Money(totalwithvat);
}
}
}
for update plugins, if the value has not been changed then it will not appear in the target entity. Therefore you should create a pre entity image an include these values, or you can create a post entity image to see the state of the entity after the changes will be applied

How do I convert a trigger to an Apex class

I need to transfer the below trigger logic to an apex class. But in apex class I cant use Trigger.New as it will give error. Once I give the logic in apex call, I can call the method in trigger so, Can anybody please tell me that how can I convert this trigger to an apex class?
trigger updatecontactrolecount on Opportunity(before insert, before update) {
Boolean isPrimary;
Integer iCount;
Map < String, Opportunity > oppty_con = new Map < String, Opportunity > (); //check if the contact role is needed and add it to the oppty_con map
for (Integer i = 0; i < Trigger.new.size(); i++) {
oppty_con.put(Trigger.new[i].id,
Trigger.new[i]);
}
isPrimary = False;
for (List < OpportunityContactRole > oppcntctrle: [select OpportunityId from OpportunityContactRole where(OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in : oppty_con.keySet())]) {
if (oppcntctrle.Size() > 0) {
isPrimary = True;
}
}
iCount = 0;
for (List < OpportunityContactRole > oppcntctrle2: [select OpportunityId from OpportunityContactRole where(OpportunityContactRole.OpportunityId in : oppty_con.keySet())]) //Query for Contact Roles
{
if (oppcntctrle2.Size() > 0) {
iCount = oppcntctrle2.Size();
}
}
for (Opportunity Oppty: system.trigger.new) //Check if roles exist in the map or contact role isn't required
{
Oppty.Number_of_Contacts_Roles_Assigned__c = iCount;
Oppty.Primary_Contact_Assigned__c = isPrimary;
}
}
You can use a TriggerHandler Class to manage your all your triggerred events in the same place:
https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices
In your trigger call your unique class :
trigger OpportunityTrigger on Opportunity (before insert,after insert,before update,after update, before delete,after delete) {
try {
new OpportunityTriggerHandler().run();
}
catch(Exception e) {
System.debug(e);
}
Then do all the logic in the TriggerHandler :
public with sharing class OpportunityTriggerHandler extends TriggerHandler {
private Map<Id, Opportunity> newOpportunityMap;
private Map<Id, Opportunity> oldOpportunityMap;
private List<Opportunity> newOpportunity;
private List<Opportunity> oldOpportunity;
public OpportunityTriggerHandler() {
this.newOpportunityMap = (Map<Id, Opportunity>) Trigger.newMap;
this.oldOpportunityMap = (Map<Id, Opportunity>) Trigger.oldMap;
this.newOpportunity = (List<Opportunity>) Trigger.new;
this.oldOpportunity = (List<Opportunity>) Trigger.old;
}
public override void beforeInsert() {
for (Opportunity o : this.newOpportunity) {
if (o.Name == '...') {
//do your stuff
}
}
}
public override void afterInsert() {
//...
}
}

Error while Inserting data in loop pne by one using Entity Framework

while inserting records in a loop
The property "id" is part of the object's key information and cannot be modified
secProductionRepository.Add(tblSecProduction);
this.SaveChanges();
CODE
Controller : This is the Controller code from where i am calling method of Repository . Adding data into repository and calling function to insert. i think i have to initialize it every time with new keyword. But where should i do that.
SingleMaster objGetXMLData = _iSingleService.GetXMLData();
if (objGetXMLData._tblSecDoorXMLData != null)
{
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}
}
Repository : Here i am inserting new row into the table
public void UpdatetblSecDoorsProduction(tblSecDoorsProduction tblSecDoorsProduction, string Message)
{
var secDoorsProductionRepository = Nuow.Repository<tblSecDoorsProduction>();
tblSecDoorsProduction alreadyAttached = null;
if (Message == "Insert")
{
secDoorsProductionRepository.Add(tblSecDoorsProduction);
Nuow.SaveChanges();
}
}
Create new object each time in the loop. Updated code here:
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
tblSecDoorsProduction _tblSecDoorsProduction = new tblSecDoorsProduction();
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}

Create querydsl predicate from map

I need help creating a predicate to use with Spring data and querydsl. I'm in the process of converting Daos to Repositorys. And I came across one that has a dynamic query in it. I can create a predicate from a list, but I'm lost at how to create a a dynamic predicate from a map. Here is the code from the DaoImpl that I'm converting from:
public Set<String> getDocumentsByDocumentAssociation(Map.Entry<String,String>[] associations) {
String queryStr = "SELECT da FROM DocumentExternalAssocEntity as da WHERE";
StringBuilder sb = new StringBuilder(queryStr);
//loop through inputs. for first loop, skip appending the OR statements. Append OR for all others
for ( int i = 0; i < associations.length; i++ ){
if ( i > 0 ) {
sb.append(" OR");
}
String whereString = " (da.associationtype = :docAssocType" + i + " AND da.associationvalue = :docAssocValue" + i + ")";
sb.append(whereString);
}
//query when previous loop is done appending
final Query query = em.createQuery(sb.toString());
for( int i = 0; i < associations.length; i++ ) {
query.setParameter("docAssocType" + i, associations[i].getKey());
query.setParameter("docAssocValue" + i, associations[i].getValue());
}
And here is the relevant generated class:
private static final long serialVersionUID = 1971644089L;
public static final QDocumentExternalAssocEntity documentExternalAssocEntity = new QDocumentExternalAssocEntity("documentExternalAssocEntity");
public final StringPath associationtype = createString("associationtype");
public final StringPath associationvalue = createString("associationvalue");
Thanks, and let me know if you need any additional info
This should do it:
BooleanExpression expr = null;
for ( int i = 0; i < associations.length; i++ ){
BooleanExpression innerExpr =
documentExternalAssocEntity.associationtype.eq(associations[i].getKey())
.and(documentExternalAssocEntity.associationvalue.eq(associations[i].getValue()))
if (expr == null) {
expr = innerExpr;
} else {
expr = expr.or(innerExpr);
}
}

salesforce trigger code coverage stuck at 35% no matter what i do

hi i am new to saleforce apex codiing and i have written a trigger which on lead conversion trasnfers a custom object to both the account and contact.(deals/offer). i have written the trigger and the test code for it but i am stuck at 35% code coverage can u please point out where i am going wrong
here is the trigger that i have written
trigger TransferDeals on Lead (after update) {
Map<Id, Lead> leadMap = new Map<Id,Lead>();
Lead parent;
for (Integer i = 0; i < Trigger.new.size(); i++){
if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false) {
leadMap.put( Trigger.new[i].Id, Trigger.new[i]);
}
}
if( leadMap.size() > 0 ) {
Set<Id> leadIds = leadMap.keySet();
List<Deal_Offer__c> allChildren =
[select Id, Account__c, Contact__c, Lead__c from Deal_Offer__c where lead__c in :leadIds];
System.debug(allChildren);
for ( Deal_Offer__c child : allChildren ) {
if ( leadMap.containsKey( child.Lead__c ) ) {
// lookup the parent lead
parent = leadMap.get( child.Lead__c );
// update the fields on the child object
child.account__c = parent.ConvertedAccountId;
child.Contact__c = parent.ConvertedContactId;
}
}
System.debug(allChildren);
//try {
update allChildren;
// } catch( Exception e ) {
// could put something here to notify on error
// otherwise it fails silently
// }
}
}
and here is the test class that i have writen to validate the code
#isTest
private class Leadtriggertest {
static testMethod void verifyAccount(){
// Perform our data preparation.
List<Lead> leads = new List<Lead>{};
List<Deal_Offer__c> deals = new List<Deal_Offer__c>{};
for(Integer i = 0; i < 200; i++){
Lead a = new Lead(LastName = 'TestLead ' + i,Company = 'TesCompany' + i,IsConverted=false);
Deal_Offer__c b = new Deal_Offer__c(Name = 'TestDeal' + i,Lead__c = a.Id);
leads.add(a);
deals.add(b);
}
insert leads;
insert deals;
Map<Id, Lead> leadMap = new Map<Id,Lead>();
Set<Id> leadIds = leadMap.keySet();
List<Lead> allChildren = [select Id,LastName,IsConverted from Lead where Id in :leadIds];
for ( Lead child : allChildren ) {
if(child.IsConverted==false){
child.Isconverted = true;
}
}
// Start the test, this changes governor limit context to
// that of trigger rather than test.
test.startTest();
// Insert the Account records that cause the trigger to execute.
update Leads;
// Stop the test, this changes limit context back to test from trigger.
test.stopTest();
List<Deal_Offer__c> testdealsupdate =
[select Id, Account__c, Contact__c, Lead__c from Deal_Offer__c where lead__c in :leadIds];
List<echosign_dev1__SIGN_Agreement__c> testagreementupdate =
[select Id, echosign_dev1__Account__c, echosign_dev1__Recipient_Lead__c from echosign_dev1__SIGN_Agreement__c where echosign_dev1__Recipient_Lead__c in :leadIds];
List<Lead> leadcheckout =
[select Id,LastName,ConvertedAccountId,ConvertedContactId from Lead where Id in :leadIds];
Map<Id,Lead> leadmap2= new Map<Id,Lead>();
for(Lead c: leadcheckout){
leadmap2.put( c.Id, c);
}
for(Deal_offer__c a : testdealsupdate){
Lead b = leadMap2.get(a.Lead__c);
System.assertEquals(a.Account__c,b.ConvertedAccountId);
System.assertEquals(a.Contact__c,b.ConvertedContactId);
}
for(echosign_dev1__SIGN_Agreement__c a : testagreementupdate){
Lead b = leadMap2.get(a.echosign_dev1__Recipient_Lead__c);
System.assertEquals(a.echosign_dev1__Account__c ,b.ConvertedAccountId);
}
}
}
please help me figure out how to increase the code coverage thank you in advance
I believe it's because this part of the code is not being executed (or rather the if condition in there).
for ( Deal_Offer__c child : allChildren ) {
if ( leadMap.containsKey( child.Lead__c ) ) {
// lookup the parent lead
parent = leadMap.get( child.Lead__c );
// update the fields on the child object
child.account__c = parent.ConvertedAccountId;
child.Contact__c = parent.ConvertedContactId;
}
Can you verify by adding an system.debug statement in the if statement?
Also, try printing out all of the lead id's in the map, and the corresponding child.Lead__c value that you are using in the line leadMap.containsKey (child.Lead__c).
Anup