Create a test method to a class - Force.com - testing

Can anyone help me to create a test method for the following class. The basic idea of this code is to clone a patent with all child elements and just change the date.
public class NovoDia {
//added an instance varaible for the standard controller
private ApexPages.StandardController controller {get; set;}
// add the instance for the variables being passed by id on the url
private Itinerario_Diario__c po {get;set;}
private Itinerario_Diario__c pi {get;set;}
// set the id of the record that is created -- ONLY USED BY THE TEST CLASS
public ID newRecordId {get;set;}
// initialize the controller
public NovoDia(ApexPages.StandardController controller) {
//initialize the stanrdard controller
this.controller = controller;
// load the current record
po = (Itinerario_Diario__c)controller.getRecord();
}
// method called from the VF's action attribute to clone the po
public PageReference cloneWithItems() {
// setup the save point for rollback
Savepoint sp = Database.setSavepoint();
Itinerario_Diario__c newPO;
try {
//copy the purchase order - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
po = [select Dia__c from Itinerario_Diario__c where id = :po.id];
newPO = po.clone(false);
insert newPO;
// set the id of the new po created for testing
newRecordId = newPO.id;
// copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE
List<Viagem__c> items = new List<Viagem__c>();
//PI.Dia__c = PO.Dia__c;
for (Viagem__c pi : [Select Cliente__c,Inicio_planejado__c,Entrada_Sa_da_de_Turno__c,Meio_de_Solicitacao__c,Motorista__c,Rota__c,Tipo_de_Viagem__c,Turno__c,Veiculo__c From Viagem__c p where Itinerario_Diario__c = :po.id ]) {
Viagem__c newPI = pi.clone(false);
newPI.Itinerario_Diario__c = newPO.id;
//newPI.Dia__c = PO.Dia__c;
items.add(newPI);
}
insert items;
} catch (Exception e){
// roll everything back in case of error
Database.rollback(sp);
ApexPages.addMessages(e);
return null;
}
return new PageReference('/'+newPO.id+'/e?retURL=%2F'+newPO.id);
}
I really appreciate the help.
Thanks
Sylvio

static testmethod void NovoDia_Test(){
Itinerario_Diario__c itinerarioDiario= new Itinerario_Diario__c();
insert itinerarioDiario;
ApexPages.StandardController sc = new ApexPages.StandardController(itinerarioDiario);
NovoDia cttr = new NovoDia (sc);
cttr.cloneWithItems();
}

Related

Error in apex test logs: common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject"

Here is what i tried. I think the problem is somewhere in the test class when i create the apex test controller and i want to link the record of the controller to the solution that i created in the test class.
This is the error that i found in logs:
"common.apex.runtime.impl.ExecutionException: List has no rows for assignment to SObject"|0x4888dd3c
apex class:
public with sharing class SolutionWrapper {
public ApexPages.StandardSetController controller;
public Opportunity opp{get; set;}
public Solutions__c oppId{get; set;}
public Solutions__c sol{get; set;}
public Solutions__c solution{get; set;}
public Account acc{get; set;}
public SolutionWrapper(ApexPages.StandardSetController controller) {
try{
solution = new Solutions__c();
solution = (Solutions__c)controller.getRecord();
if(solution.Id != null){
oppId = [SELECT id, Solutions__c.Opportunity__c
FROM Solutions__c
WHERE id =: solution.Id
LIMIT 1];
opp = [Select id,Name, AccountId, CurrencyIsoCode from
Opportunity where id =: oppId.Opportunity__c LIMIT:1];
}
if(opp.id !=null){
sol = [SELECT id,Name, Mail_Merge_Id__c,Solution_Country__c, Solutions__c.Opportunity__c
FROM Solutions__c
WHERE Solutions__c.Opportunity__c =: opp.id
LIMIT 1];
acc = [Select id,Name,Country__c from
Account where id=:opp.AccountId LIMIT: 1];
}
}
catch(Exception e){
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,e.getMessage()));
}
}
}
Here is my test class
apex test class:
#isTest
public class SolutionWrapperTest {
static testMethod void testMethodOpp(){
Account acc = new Account(Name='test', Country__c='test');
insert acc;
Opportunity opp = new Opportunity(Name='test', AccountId=acc.id, CurrencyIsoCode='GBP', StageName = 'Good',
CloseDate = date.today());
insert opp;
Solutions__c sol = new Solutions__c( Opportunity__c= opp.id, CurrencyIsoCode='GBP');
insert sol;
List<Solutions__c> listSol = new List<Solutions__c>();
listSol.add(sol);
PageReference pageRef = Page.NewVisualForcePage;
Test.setCurrentPage(pageRef);
Test.startTest();
ApexPages.StandardSetController stdController = new ApexPages.StandardSetController(listSol);
SolutionWrapper testSolution = new SolutionWrapper(stdController);
Test.stopTest();
}
}
Solution id is different from the one that i inserted in the test class. I inserted a dummy value (eq 'test') on a field like Currency. After that i selected from the db based on Currency instead of id.

Batch Class Add contact to Account

I have created 20 records with the 'name=SampleAccountOne'. I am trying to create a batch class that will add a given contact to the 20 records. Stuck with syntax and where to go. Any help in the right direction is greatly appreciated.
global class UpdateProjectNameBatch implementsDatabase.Batchable<sObject> {
List<Contact> conList = new conList<Contact>();
String query = 'Select Id,Name FROM Account WHERE Name = \'SampleAccountOne\''
global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc,List<sObject> batch){
for(Contact c : conList){
batch.c = 'New Contact Name';
}
}
global void finish(){
}
}
I believe you are trying to associate a single contact to multiple accounts. This functionality was released in Spring 16' and is implemented through a Salesforce Junction object - AccountContactRelation.
I assume you have already enabled this functionality through the UI and a parent Account is declared for this Contact.
I have modified your code to associate the contact to all 20 account.
global class UpdateProjectNameBatch implements Database.Batchable
<sObject>
{ ID conId = '0037F00000IfCCKQA3'; //Add the contact Id here
List<AccountContactRelation> ListInsertion = new List<AccountContactRelation>();
String query = 'Select Id,Name FROM Account WHERE Name = \'SampleAccountOne\'';
global Database.QueryLocator start(Database.BatchableContext bc)
{
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc,List<Account> batch){
for (Account a : batch)
{
AccountContactRelation c = new AccountContactRelation();
c.AccountId = a.id;
c.contactId = conId;
ListInsertion.add(c);
}
Insert ListInsertion;
}
global void finish(Database.BatchableContext bc)
{
//DoNothing.
}
}

Apex test class - trigger not firing

I wrote an apex trigger to update a field (status_update_date) when an account's status is changed.
In the sandbox, if I change an account's status, the status_update_date successfully updates.
When I run my test class, the trigger does not get called and I get a null value for the status_update_date. Any ideas why the trigger is not called? Thanks!
Code below with trigger commented out at bottom of code:
#isTest
private class UpdateStatusTest{
public static Account A;
public static String initStatus = '';
public static String finalStatus = 'Fully Active';
static testMethod void testWithAccount() {
A = new Account(
Status__c = initStatus,
Name = 'TestName'
);
insert A;
test.StartTest();
A.Status__c = finalStatus;
update A;
test.StopTest();
// System.assertEquals(finalStatus, A.Status__c);
System.assertEquals(system.today(),A.Status_Update_Date__c);
}
}
// trigger UpdateStatus on Account (before update) {
//for(Account a: trigger.new){
//If the status has changed, update the date
// if (trigger.oldMap.get(a.Id).Status__c != trigger.newMap.get(a.Id).Status__c) {
// a.Status_Update_Date__c = system.today();
// }
//}
//}
After update you should get this record from database by soql
a=[SELECT Id, Status__c FROM Account WHERE Id=:a.Id];
System.assertEquals(finalStatus, A.Status__c);

not able to create constructor of model class and getting object reference not set to instance of object error

this is my Model:
public class UserDetails
{
public string UserName { get; set; }
public virtual Category Category { get; set; }
}
this is my query to fetch user details along with category:
var data = (from temp in context.UserDetails.Include("Category") select temp).OrderBy(c => c.UserId);
this is how i am accessing on controller:
List<UserDetails> staffDetails = staffBal.fetchStaffDetails();
var categoryModel = new CategoryModel();
Data = staffDetails.Select(x =>
{
var userDetailModel = new UserDetailsModel();
userDetailModel.UserId = x.UserId;
userDetailModel.FName = x.FName;
categoryModel.CategoryName = x.Category.Name;//i am getting error on this line.object reference not set to instance of object
can anybody tell me what is the solution???
You say in your comment: for some records it is coming null for some records it is not null meaning that x.Category is null. Therefore, any attempt to access x.Category.Name will fail. Change the line to this:
categoryModel.CategoryName = x.Category == null ? "" : x.Category.Name;

NHibernate UniqueKey not being enforced

I have a class on which I'd like to define a unique key using Fluent NHibernate. I think I've done this correctly, but my unit tes,t in which I save two objects with the same value for the field in question, saves both items without error. Here's what I've got:
Mapping override:
public class ItemOverride : IAutoMappingOverride<Item>
{
#region IAutoMappingOverride<Item> Members
public void Override(AutoMapping<Item> mapping)
{
mapping.Map(t => t.Prompt).UniqueKey("UIX_Item_Prompt").Not.Nullable();
}
#endregion
}
Unit Test
[Test]
public void CannotSaveDuplicateItemPrompt()
{
ServiceLocatorInitializer.Init();
IItemManagementService itemManagementService = new ItemManagementService(repository);
Item first = ItemInstanceFactory.CreateValidTransientItem();
first.Prompt = "Duplicate";
itemManagementService.SaveOrUpdate(first);
Item second = ItemInstanceFactory.CreateValidTransientItem();
second.Prompt = "Duplicate";
ActionConfirmation confirm = itemManagementService.SaveOrUpdate(second);
Assert.IsFalse(confirm.WasSuccessful);
Assert.AreEqual(confirm.Message, "");
}
Okay, it works if I wrap the two saves in a transaction. Here's the new Unit Test:
[Test]
[ExpectedException(typeof(GenericADOException))]
public void CannotSaveDuplicateItemPrompt()
{
ServiceLocatorInitializer.Init();
IItemManagementService itemManagementService = new ItemManagementService(repository);
NHibernateSession.Current.BeginTransaction();
Item first = ItemInstanceFactory.CreateValidTransientItem();
first.Prompt = "Duplicate";
itemManagementService.SaveOrUpdate(first);
Item second = ItemInstanceFactory.CreateValidTransientItem();
second.Prompt = "Duplicate";
ActionConfirmation confirm = itemManagementService.SaveOrUpdate(second);
NHibernateSession.Current.Transaction.Commit();
}