Salesforce Test class getting System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set Error - apex

I have written a trigger and handler class (which uses a future method) and it works well. I am really struggling to write the test class for it. My first problem is that the code coverage is high (before tweaks it was 0% in the handler class). After tweaking, I am getting the following error:
System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set
I am not sure how to solve this and I am a pretty new dev so not sure what to do next . Can someone please help?
Here is my code:
Trigger:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(str);
}
}
}
Handler:
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test class:
#isTest
public class AccountTriggerKeepAcctTeamTest {
//#TestSetup
static testMethod void AcctOwnerChange(){
List<User> userList = TestDataFactory.createUser(true, 2);
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u1 = new User(Alias = 'standt', Email='standarduser#testorg1.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg01.com');
insert u1;
User u2 = new User(Alias = 'standt', Email='standarduser#testorg2.com',
EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg92.com');
insert u2;
System.runAs(u1){
Allowed_Account_Owner_Change__c setting = new Allowed_Account_Owner_Change__c();
setting.Allowed_to_change_Account_Owner__c = true;
insert setting;
fferpcore__ExchangeRateGroup__c exrg = new fferpcore__ExchangeRateGroup__c(CurrencyISOCode = 'USD', fferpcore__DefaultCurrency__c = 'USD - U.S. Dollar', Name = 'FF Shared Test Group', fferpcore__SelectedCurrencies__c = 'USD - U.S. Dollar');
insert exrg;
c2g__codaCompany__c company = new c2g__codaCompany__c();
company.Name = 'ApexTestCompany';
company.RecordTypeId = Schema.SObjectType.c2g__codaCompany__c.RecordTypeInfosByName.get('SUT').RecordTypeId;
insert company;
company.c2g__ExchangeRateGroup__c = exrg.Id;
update company;
Account acc = new Account(Name = 'Test Acc2', NumberOfEmployees = 500);//TestDataFactory.createAccountwithCurrencyMaster(true);
acc.OwnerId = userinfo.getUserId();
insert acc;
AccountTeamMember accTeam = new AccountTeamMember();
accTeam.UserId = acc.OwnerId;
accTeam.AccountAccessLevel = 'Read';
accTeam.AccountId = acc.Id;
insert accTeam;
System.debug('## User '+userinfo.getUserName());
//create opportunity
//}
// }
// static testMethod void testAcctOwnerChange(){
// User u = [Select id, LastName from User where LastName = 'Testing2'];
// Account acc = [Select id, OwnerId from Account Limit 1];
Test.startTest();
acc.OwnerId = u2.id;
update acc;
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(JSON.serialize(acc));
//System.assertEquals(accTeam.UserId,u2.Id);
Test.stopTest();
//AccountTeamMember atm = [Select userId,AccountId, AccountAccessLevel from AccountTeamMember where AccountId =: acc.Id];
}
}
Can someone please help? I am a beginner apex dev
Trigger Attempt for Alin's test class:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
Set<Id> accteammbrId = new Set<Id>();
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
//system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
//String str = JSON.serialize(listAcc);
for(AccountTeamMember actmbr : listAcc){
accteammbrId.add(actmbr.Id);
}
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(accteammbrId);
}
}
}
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(Set<Id> AccteambrId){
List<AccountTeamMember> newlistAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in :AccteambrId];
//system.debug('Future call '+str);
//List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
//system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
system.debug('Account records to insert' + newlistAcc);
Upsert newlistAcc;
}
}

I don't understand why you have to serialize the list in the first place.
Change your retainOldTeamMemberOnOwnerChange to accept a List as parameter and don't use the JSON at all.
Then in your test class you create an account, assign an account team to it and change the owner. After that you will query the List of associated AccountTeamMember and assert it with regards to the AccountTeamMember before the ownership of the account was changed.
If it's not clear enough I can give you a code example, but I think the exercise will be good for you.
Edit: I see. My bad. This is what I use for test coverage. I can also provide code sample from the trigger if needed.
Trigger:
trigger AccountTrigger on Account (before update, After Update) {
if(trigger.isBefore){
if(trigger.isUpdate){
AccountTriggerHandler.retainAccountTeam(trigger.new, trigger.oldMap);
}
}
}
Handler:
public class AccountTriggerHandler {
public static void retainAccountTeam(List<Account> newList, Map<Id, Account> oldMap) {
Set<Id> accountsWithNewOwners = new Set<Id>();
for(Account acc : newList){
if(acc.OwnerId != oldMap.get(acc.Id).OwnerId){
accountsWithNewOwners.add(acc.Id);
}
}
if(accountsWithNewOwners.size() > 0){
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember WHERE AccountId IN :accountsWithNewOwners];
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
// delete team member records if required
retainOldTeamMemberOnOwnerChange(str);
}
}
//Before Update calls the future method that basically reinserts the Account Team member records. You can also consider deleting the Account Team Member records before calling the future method.
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test method:
static testMethod void test_retainAccountTeam(){
Id mhbkRTId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('MHBK').getRecordTypeId();
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u = new User(
Alias = 'rivacon',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector#testorg.com');
insert u;
User u2 = new User(
Alias = 'updated',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva2',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector2#testorg.com');
insert u2;
system.runAs(u){
Account acc = new Account(RecordTypeId = mhbkRTId,Name = 'test',Branch__c='London',Industry='Banking',Year_Founded__c='1900',BillingStreet = '1 Long Rd',BillingCity = 'City',CurrencyIsoCode = 'GBP');
insert acc;
AccountTeamMember atm = new AccountTeamMember();
atm.AccountId = acc.Id;
//atm.Name ='Test ATM';
atm.TeamMemberRole = 'Sales Assistant';
atm.UserId = u.Id;
insert atm;
Test.startTest();
acc.OwnerId = u2.Id;
update acc;
Test.stopTest();
System.debug('usr1 ' + u.id);
System.debug('usr2 ' + u2.id);
Account updatedAccount = [SELECT OwnerId FROM Account WHERE Id = :acc.Id];
system.assertEquals(u2.Id, updatedAccount.OwnerId);
List<AccountTeamMember> teamMembers = [SELECT Id, AccountAccessLevel, AccountId, UserId, TeamMemberRole, Title FROM AccountTeamMember WHERE AccountId = :acc.Id];
system.assertEquals(1, teamMembers.size());
system.assertEquals(teamMembers[0].TeamMemberRole, atm.TeamMemberRole);
}

Related

C# ExecuteReaderAsync Sporadic Issue

I have a method that is getting a list of users. There is a store procedure that is expected either a username or null. It returns one or more users based on the parameter. It works fine most of the time, but I notice there are times it does not return any result even though I am passing the same exact parameter. I put a break point in the Execute Reader Async, and the line immediately following it. When the issue occurs, it reaches the first break point but not the second one. It does not throw an exception or prevent me from making another call. I can make the next call, and it will return the result as expected. I would appreciate some suggestions as to what may cause this issue?
public async Task<List<User>> GetUsers(string username, int accountType = 1)
{
List<User> users = null;
parameters = new List<SqlParameter>{
new SqlParameter{
DbType = DbType.String,
ParameterName = "#userName",
Value = username.NotEmpty() ? username : (object) DBNull.Value
},
new SqlParameter{
DbType = DbType.Int32,
ParameterName = "#accountType",
Value = accountType
}
};
try
{
using (SqlConnection con = new SqlConnection(conStr))
{
await con.OpenAsync();
using (SqlCommand cmd = new SqlCommand("spGetUsers", con))
{
cmd.Parameters.AddRange(parameters.ToArray());
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = await cmd.ExecuteReaderAsync()
if (dr.HasRecord())
{
while (await dr.ReadAsync())
{
User user = new User();
user.FirstName = dr["firstName"].ToString();
user.LastName = dr["lastName"].ToString();
user.DateRegister = Convert.ToDateTime(dr["DateRegister"].ToString());
user.Active = Convert.ToBoolean(dr["Active"].ToString());
if(users == null)
{
users = new List<User>();
}
users.Add(user);
}
}
}
}
}
catch (Exception ex)
{
Util.LogError(ex.ToString());
users = null;
}
return users;
}
Update:
Yes, the error is being logged. Also, I added a breakpoint in the catch statement in case an error is thrown.
Here is the query that is used to create that store procedure:
IF EXISTS (SELECT 1 FROM SYS.objects WHERE object_id = OBJECT_ID('spGetUsers') AND TYPE IN (N'PC', N'P'))
DROP PROCEDURE spGetUsers
GO
CREATE PROCEDURE spGetUsers
#userName nvarchar(50),
#accountType int = 1
AS
BEGIN
SELECT U.firstName, U.lastName, U.DateRegister, A.Active
FROM [User] U
inner join UserAccount UA
on U.Id = UA.userid
inner join Account A
on A.Id = UA.accountId
WHERE U.Id > 0
AND UA.Id > 0
AND A.Id > 0
AND UA.AccountType IN (#accountType )
and (A.UserName in (#userName) or #userName IS NULL)
END
Extension Method to check if SQL DataReader has record
public static bool HasRecord(this System.Data.SqlClient.SqlDataReader dr)
{
if (dr != null && dr.HasRows)
{
return true;
}
return false;
}

Regarding Trigger email

I have a trigger code:
Trigger AutoEmailsending on Order (after update)
{
Map<Id,Order> Orderdetail = new Map<Id,Order>();
Set<Id> Accountid = new Set<Id>();
for(order or1 : Trigger.new)
{
if(or1.Status == 'Submitted' && (or1.Subtype__c =='Offer' || or1.Subtype__c =='ASP'))
{
Orderdetail.put(or1.id,or1);
Accountid.add (or1.accountid);
}
}
List<Attachment> Attachmentlst = [Select Id,
ParentId,
Name,
BodyLength,
Body,
Description
From Attachment
where ParentId=:Orderdetail.keyset()];
Map<String, Blob> resources = new Map<String, Blob>();
for(StaticResource resource:[SELECT Name, Body FROM StaticResource where Name IN ('TC_for_France','TC_for_Italy')])
{
resources.put(resource.Name, resource.Body);
}
User currentUser = [Select Id,Phone,name from User where Id =:System.UserInfo.getUserId()];
for (attachment attachmentlst1 : attachmentlst )
{
List<String> Toaddress = new List<String>();
List<String> CCaddress = new List<String>();
String Orderid = attachmentlst1.ParentId;
String ResourceName;
String TCname;
string strHtmlBody;
String Emailaddress = UserInfo.getUserEmail();
String CustomerServiceEmail = Order_Configuration__c.getInstance().Customer_Service_Email__c;
string SellingOfficePhone = Order_Configuration__c.getInstance().Selling_Office_Phone__c;
String OrderNumber = Orderdetail.get(attachmentlst1.ParentId).OrderNumber;
List<Messaging.Emailfileattachment> fileAttachments = new List <Messaging.Emailfileattachment>();
if(Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Email_Address__c != null)
{
Toaddress.add(Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Email_Address__c);
}
String Market = Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Market__c;
CCaddress.add(emailaddress);
if(CustomerServiceEmail !=null)
CCaddress.add(CustomerServiceEmail);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(Toaddress);
mail.setCcAddresses(CCaddress);
if(Orderdetail.get(attachmentlst1.ParentId).Subtype__c =='Offer' || Market=='FR')
{
mail.setSenderDisplayName('Trade Order-FR');
ResourceName = 'TC_for_France';
TCname = 'CONDITIONS_GENERALES_DEVENTE.pdf';
}
}
The trigger should send mail for the created user of the particular order,it should not send mail for last modified user of Particular order How to over come this Scenario,Dont need about the logic what i have to add lines in the trigger code

Salesforce Trigger to populate a lookup field

I am trying to create salesforce trigger on Lead that auto-populates a look up field which links the current Lead to an existing Account if there exist an Account with the same name as the Lead's Company custom field.
This is my code:
trigger Link_Lead_To_Account on Lead (before insert ) {
Set<String> whatIDs = new Set<String>();
MAP<id,String> accountMap= new MAP<id,String>();
// save the leads that have been triggered
for (Lead l : Trigger.new) {
whatIDs.add(l.id);
}
List<Lead> leads = [SELECT Id,Company FROM Lead where ID=:whatIDs ];
// loop through the triggered leads, if the account.name == to lead.company then link the found account to the lead
for (Integer i = 0; i <Trigger.new.size(); i++)
{
// System.Debug('++++++++++++++'+Trigger.new[i].company+Trigger.new[i].id);
if(accountMap.get(Trigger.new[i].company)!=null)
{
for(Account ac :[Select name,id from Account])
{
if(Trigger.new[i].Company==ac.Name)
{
Trigger.new[i].Account__c= ac.id;
break;
}
}
}
// System.Debug('Trigger.new[i].Account__c::::'+Trigger.new[i].Account__c);
// System.Debug('Trigger.new[i].company:::::'+Trigger.new[i].company);
// System.Debug('Trigger.new[i].ID:::::'+Trigger.new[i].ID);
}
update leads;
}
But it doesn't work at all. It throws the following error:
Review all error messages below to correct your data.
Apex trigger Link_Lead_To_Account caused an unexpected exception, contact your administrator: Link_Lead_To_Account: execution of AfterInsert caused by: System.StringException: Invalid id: TestAccount2: External entry point
As it requires the Company field to be an ID, but when I write an ID it does't perform any changes.
I managed to fix it.
This is the working class where newLeads.Values() is being populated in the constructor with to the Trigger.new() values on the before insert event:
public void LinkLeadToAccount() {
Set<String> companies = new Set<String>();
for (Lead l: newLeads.values()) {
if (l.Company != null) companies.add(l.Company);
}
if (companies.size() > 0) {
// Pick most recent Account where more than one with same name
Map<String, Id> accountNameToId = new Map<String, Id>();
for (Account a : [
select Name, Id
from Account
where Name in :companies
order by CreatedDate
]) {
accountNameToId.put(a.Name, a.Id);
}
if (accountNameToId.size() > 0) {
Lead[] updates = new Lead[] {};
for (Lead l: newLeads.values()) {
if (l.Company != null) {
Id accountId = accountNameToId.get(l.Company);
if (accountId != null) {
updates.add(new Lead(Id = l.Id, Account__c = accountId));
}
}
}
System.debug(' leads_to_update : ' + updates.size() + ' leads_to_update : ' + updates);
update updates;
}
}
}

Attempt to dereference a Null object Salesforce

I have made a trigger to update the Contact ID in person account and its working for person accounts it is populating the Contact ID field on person account.
The problem is it is giving an error on business and employer account record type i have also inserted a check for record type. But still its giving an error
on Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UpdateContactID caused an unexpected exception, contact your administrator: UpdateContactID: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateContactID: line 41, column 1
The trigger is below:
trigger UpdateContactID on Account (after insert, after update)
{
//Identify applicable record type
RecordType PersonAccount = [SELECT Id FROM RecordType WHERE SobjectType='Account' AND Name = 'Career Champion Account' limit 1];
List<Account> toUpdate = new List<Account>();
if(trigger.isInsert)
{
List<String> newAccountIDList = new List<String>();
// Taking all account IDs in collection
for(Account acct: Trigger.new)
{
newAccountIDList.add(acct.ID);
}
// Fetching contacts against the account IDs
List<Contact> contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList];
// Adding contacts in a map with relation to Account ID
Map<String, Contact> mapContact = new Map<String, Contact>();
for(Contact cont : contactList)
{
mapContact.put(cont.Account.Id, cont) ;
}
// Updating Contact_ID__c from Map to new Account list to update
List<Account> newAccounts = [select Id, Contact_ID__c from Account where Id in :newAccountIDList];
for(Account acct: newAccounts)
{
**LINE 41**
toUpdate.add(new Account(
id = acct.Id,
Contact_ID__c = mapContact.get(acct.Id).Id
));
}
update toUpdate;
} // if
else if(trigger.isUpdate && trigger.new[0].Contact_ID__c == null && trigger.old[0].Contact_ID__c == null)
{
List<String> newAccountIDList = new List<String>();
// Taking all account IDs in collection
for(Account acct: Trigger.new)
{
newAccountIDList.add(acct.ID);
}
// Fetching contacts against the account IDs
List<Contact> contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList];
// Adding contacts in a map with relation to Account ID
Map<String, Contact> mapContact = new Map<String, Contact>();
for(Contact cont : contactList)
{
mapContact.put(cont.Account.Id, cont) ;
}
// Updating Contact_ID__c from Map to new Account list to update
List<Account> newAccounts = [select Id, Contact_ID__c from Account where Id in :newAccountIDList];
// List<Account> toUpdate = new List<Account>();
for(Account acct: newAccounts)
{
toUpdate.add(new Account(
id = acct.Id,
Contact_ID__c = mapContact.get(acct.Id).Id
));
}
update toUpdate;
} // else if
} // trigger
Most likely mapContact does not contain a value for the key acct.Id. The mapContact.get(acct.Id) call will return null and the following .Id will give the null reference exception.
You should add a guard statement before that line. E.g.
if(mapContact.containsKey(acct.Id)) {
toUpdate.add(new Account(
id = acct.Id,
Contact_ID__c = mapContact.get(acct.Id).Id
));
}

Apex - Test class adding Chatter Free users

I'm a newbie trying to build a test class for a registration handler that allows new chatter free users to be created for an org. To create the chatter free user, the working trigger checks a new user's email domain against a predefined list of acceptable email domains that are stored in a custom object named DomainList.
Looking for suggestions on how to better structure a test class for code coverage. Any ideas appreciated, thanks!
global class RegHandlerDomain implements Auth.RegistrationHandler {
global User createUser(Id portalId, Auth.UserData data) {
String domain = data.email.split('#')[1];
List<DomainList__c> listedDomains = [SELECT id,
name
FROM DomainList__c
WHERE Email_Domain__c = : domain];
if (listedDomains.size() == 1) {
User u = new User();
Profile p = [SELECT Id
FROM profile WHERE name = 'Chatter Free User'];
// Use incoming email for username
u.username = data.email;
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
u.alias = (data.username != null) ? data.username : data.identifier;
if (u.alias.length() > 8) {
u.alias = u.alias.substring(0, 8);
}
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = 'America/Los_Angeles';
u.profileId = p.Id;
System.debug('Returning new user record for ' + data.username);
return u;
} else return null;
}
global void updateUser(Id userId, Id portalId, Auth.UserData data) {
User u = new User(id = userId);
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
System.debug('Updating user record for ' + data.username);
update(u);
}
}
Test class is looking for a '}' before the insert
#isTest(SeeAllData = true)
public class RegHandlerTest {
public void myTestMethod1() {
//CREATE CHATTER FREE TEST USER
Profile p = [select id
from profile where name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
}
//CHECK NEW USER EMAIL DOMAIN TO SEE IF IN CUSTOM OBJECT DOMAINLIST
List<DomainList__c> listedDomains = [select id, email_domain__c
from DomainList__c
where name = 'testorg' LIMIT 1];
if (listedDomains.size() == 1) System.debug('WORKS');
}
Fir of all you need create a proper unit test, because your is not correct.
#isTest(SeeAllData = true)
public class RegHandlerTest {
#isTest private static void verifyInsertChatterFreeUser() {
//CREATE CHATTER FREE TEST USER
Profile p = [SELECT id
FROM profile
WHERE name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
// perform some assertions regarding expected state of user after insert
//CHECK NEW USER EMAIL DOMAIN TO SEE IF IN CUSTOM OBJECT DOMAINLIST
List<DomainList__c> listedDomains = [SELECT id, email_domain__c
FROM DomainList__c
WHERE name = 'testorg' LIMIT 1];
// as you've annotated class with SeeAllData=true, this assertion always will be true
System.assertEquals(1, listedDomains.size());
}
#isTest private static void verifyUpdateChatterFreeUser() {
//CREATE CHATTER FREE TEST USER
Profile p = [SELECT id
FROM profile
WHERE name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
// perform some assertion regarding expected state of user after insert
// change something on user
u1.email = 'test.chatter.free#gmail.com';
update u1;
// perform some assertions regarding expected state of user after update
// System.assertEquals('expected value', u1.field);
}
}