I have created a test class however when it runs I am getting the error message
"System.StringException: Invalid id: Test"
"Stack Trace Class.MatchReadyImageTest.MatchReadyImage: line 6, column 1"
Is there something I have done wrong?
Many thanks
Class:
public class MatchReadyImage {
public Match_Day_Check_List__c obj {get; set; }
public MatchReadyImage(){
obj = [Select Id, Match_Day_Ready_Status__c From Match_Day_Check_List__c Where Name = 'Everton V West Ham United Goodison Park EPL 2013-05-12'];
}
}
Test Class:
#isTest
public class MatchReadyImageTest {
static testMethod void MatchReadyImage() {
CS_Fixture__c fff = new CS_Fixture__c(Name = 'aaaaa', Fixture_Date__c = Date.Today(), CS_Season__c = 'Test', CS_Competition__c = 'Test', Football_Club__c = 'Test');
insert fff;
Pre_Match__c ppp = new Pre_Match__c();
insert ppp;
Match_Day_Check_List__c mmm = new Match_Day_Check_List__c(
Fixture__c = fff.id
,Match_Plan__c = ppp.id
,Name = 'Everton V West Ham United Goodison Park EPL 2013-05-12'
);
insert mmm;
Test.startTest();
MatchReadyImage con = new MatchReadyImage();
Test.stopTest();
System.assert(con.obj != null);
}
}
These fields CS_Season__c = 'Test', CS_Competition__c = 'Test', Football_Club__c = 'Test' are relationship fields, thus you have to create an appropriate records of these objects and populate fields with Ids of these records.
Related
I create this controller to diplay on a visualforce page a custom approval related list of record with the signature (photo) of Actor for an object Called Car_Maintenance. It works perfectly on my sandbox but i have trouble to write the test Class to deploy it in the production.
The Controller and my test class are below. My headache start at the line 53 in the Test Class. the error message is some field are required in the approval record.
Controller
public MaintenanceRequestController() {
}
public Map<Id,User> userMap { get; set; }
public List<ProcessInstanceStep> processInstanceList { get; set; }
public MaintenanceRequestController(ApexPages.StandardController controller) {
userMap = new Map<Id, User>();
processInstanceList = new List<ProcessInstanceStep>();
Id recordId = ApexPages.CurrentPage().getparameters().get('id');
processInstanceList = [Select id,ActorId, Actor.Name,CreatedDate, Actor.Title, Actor.FirstName , ProcessInstanceId,
Actor.LastName, StepStatus, ProcessInstance.TargetObjectId
from ProcessInstanceStep
WHERE ProcessInstance.TargetObjectId = :recordId];
for (ProcessInstanceStep step : processInstanceList){
userMap.put(step.ActorId, new User(Signature__c=null));
}
userMap.putAll([SELECT Id,Name,Signature__c FROM User WHERE Id = :userMap.keySet()]);
}
}```
test Class
```#IsTest
public class CarMaitenanceControllerTest{
static testMethod void CarMaitenanceController(){
Car__c veh = new Car__c ( Category__c='Pickup', Color__c='Red', Condition__c='Excellent',
Description__c='Test Vehicle', Engine_Number__c='XXX',
Matriculation__c = 'IT-00011', Make__c='Toyota', Year__c ='2017', Model__c='Colorado');
insert veh;
Part_Accessories_Reception__c par = new Part_Accessories_Reception__c();
par.Date__c = System.today();
par.Provider__c = 'Other';
insert par;
Part_Accessories__c pa = new Part_Accessories__c(Name = 'filter');
insert pa;
Part_Accessories_Inventory__c pai = new Part_Accessories_Inventory__c();
pai.Quantity_Received__c =7771;
pai.Part_Accessories_Reception__c = par.ID;
pai.Part_Accessories__c = pa.Id;
insert pai;
Car_Maintenance__c carMain = new Car_Maintenance__c();
carMain.Car__c = veh.ID;
carMain.Cheque_Bank__c = '444-Cmmm';
carMain.Company__c = 'FFP';
carMain.Date__c = System.today();
insert carMain;
Maintenance_Details__c mdet = new Maintenance_Details__c();
mdet.Description__c = 'qiuyiuyi';
mdet.Quantity__c =555;
mdet.Maintenance__c = carMain.Id;
mdet.Description__c ='kjalhsdhfklasdf';
mdet.Cost__c = 999;
mdet.Part_Accessories_Inventory__c = pai.Id;
insert mdet;
Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
app.setObjectId(carMain.Id);
Approval.ProcessResult result = Approval.process(app);
ProcessInstance pi = new ProcessInstance ();
pi.TargetObjectId = carMain.Id;
pi.Status ='Approved';
Insert pi;
ProcessInstanceStep pis = new ProcessInstanceStep();
pis.ProcessInstanceId = pi.Id;
Insert pis;
Test.setCurrentPageReference(new PageReference('CarMaintenanceView'));
System.currentPageReference().getParameters().put('id', veh.ID);
CarMaintenanceController CRC = new CarMaintenanceController();
MaintenanceRequestController mrc = new MaintenanceRequestController();
}
}```
Can you identify which is line 53 of the test class, the one that is giving you trouble? And the specific error?
It may be that the required fields in production are different than what's in the sandbox, and that's tripping you up when you insert your test data.
I am not familiar with EF and just following examples of a WebAPI book.
This is the error I get:
And this is the DbContext class I have:
namespace SportsStore.Models
{
public class ProductDbContext: DbContext
{
public ProductDbContext()
: base("SportsStoreDb")
{
Database.SetInitializer<ProductDbContext>(new ProductDbInitializer());
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderLine> OrderLines { get; set; }
}
}
and there is also an Initializer class like this:
using System.Collections.Generic;
using System.Data.Entity;
namespace SportsStore.Models
{
public class ProductDbInitializer : DropCreateDatabaseAlways<ProductDbContext>
{
protected override void Seed(ProductDbContext context)
{
new List<Product> {
new Product() { Name = "Kayak", Description = "A boat for one person",
Category = "Watersports", Price = 275m },
new Product() { Name = "Lifejacket",
Description = "Protective and fashionable",
Category = "Watersports", Price = 48.95m },
new Product() { Name = "Soccer Ball",
Description = "FIFA-approved size and weight",
Category = "Soccer", Price = 19.50m },
new Product() {
Name = "Corner Flags",
Description = "Give your playing field a professional touch",
Category = "Soccer", Price = 34.95m },
new Product() { Name = "Stadium",
Description = "Flat-packed 35,000-seat stadium",
Category = "Soccer", Price = 79500m },
new Product() { Name = "Thinking Cap",
Description = "Improve your brain efficiency by 75%",
Category = "Chess", Price = 16m },
new Product() { Name = "Unsteady Chair",
Description = "Secretly give your opponent a disadvantage",
Category = "Chess", Price = 29.95m },
new Product() { Name = "Human Chess Board",
Description = "A fun game for the family",
Category = "Chess", Price = 75m },
new Product() { Name = "Bling-Bling King",
Description = "Gold-plated, diamond-studded King",
Category = "Chess", Price = 1200m },
}.ForEach(product => context.Products.Add(product));
context.SaveChanges();
new List<Order> {
new Order() { Customer = "Alice Smith", TotalCost = 68.45m,
Lines = new List<OrderLine> {
new OrderLine() { ProductId = 2, Count = 2},
new OrderLine() { ProductId = 3, Count = 1},
}},
new Order() { Customer = "Peter Jones", TotalCost = 79791m,
Lines = new List<OrderLine> {
new OrderLine() { ProductId = 5, Count = 1},
new OrderLine() { ProductId = 6, Count = 3},
new OrderLine() { ProductId = 1, Count = 3},
}}
}.ForEach(order => context.Orders.Add(order));
context.SaveChanges();
}
}
}
And I was able to login to localhost db of my SQL Server engine too .
So what should I be looking at to solve the issue?
Ok finally solved it myself. Yeah nothing with connection string. Glad I didn't go to that rabbit hole that people were posting as duplicate answer.
The problem was in Web.Config the version below was 13, I changed it to 11 now it works.
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
I've got the following query:
select id, name, email, supervisor, createdBy, createdAt, changedBy, changedAt from XXX
Now, I'd like to map each row into something that looks like this:
public class Organisation{
public int Id{get; set; }
public string Name{get; set; }
public ContactInfo Contact{get;set;}
public Action CreatedBy{get;set;}
public Action ChangedBy{get;set;}
}
public class ContactInfo{
public string Name{get;set;}
public string Email{get;set;}
}
public class Action{
public string Username{get;set;}
public DateTime At{get;set;}
}
I've seen some examples that show how to partition the info, but it seems like will not work in this example. Can it be done or should I map my query into a helper object which will then be mapped into these classes?
Thanks.
Luis
Dapper allows you to map a single row to multiple objects. This is a
key feature if you want to avoid extraneous querying and eager load
associations.
You can read about it more here
Below is an example:
[Test]
public void Test_Multi()
{
using (var conn = new SqlConnection(#"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
{
var result = conn.Query<Organisation, ContactInfo, Action, Action, Organisation>(
#"select Id = 100, Name = 'Foo',
Name = 'Contact Name', Email = 'contact#foo.com',
Username = 'The Creator', At = '12/25/2017',
Username = 'The Modifier', At = '12/26/2017' ",
(org, contact, cretedBy, changedBy) =>
{
org.Contact = contact;
org.CreatedBy = cretedBy;
org.ChangedBy = changedBy;
return org;
}, splitOn: "Id, Name, Username, Username").First();
Assert.That(result.Id, Is.EqualTo(100));
Assert.That(result.Contact.Email, Is.EqualTo("contact#foo.com"));
Assert.That(result.CreatedBy.Username, Is.EqualTo("The Creator"));
Assert.That(result.ChangedBy.Username, Is.EqualTo("The Modifier"));
}
}
i have a visual force page which is used as a view to send a custom sms to the leads generated in salesforce.The year field is a number field on salesforce. Posting the controller and test class error. Also mentioning the error line.
Controller :-
//Class to send Message to Lead or Account
public class nmSendSMS
{
//Name of Lead or Account
public string strName{get;set;}
public Lead objLead {get;set;}
public String defaultNumbersToBeAdded;
public String leadYear{get;set;}
//Mobile number of lead of account
public string strMobile{get;set;}
public String messageToBeSent{get;set;}
public List<SelectOption> getYear{get;set;}
public string strSMSBody{get;set;}
//To disable fields if data is not available
String session,statusOfLead,stringOfMobileNumbers;
public nmSendSMS()
{
objLead = new Lead();
leadYear ='';
defaultNumbersToBeAdded = '9820834921,9920726538';
messageToBeSent = '';
stringOfMobileNumbers= '';
}
//Method to send SMS
public PageReference SendSMS()
{
if(leadYear!='' || messageToBeSent!='')
{
session = objLead.nm_Session__c;
integer lengthOfCommaSeperatedNumbers;
String finalString ='';
statusOfLead = objLead.Status;
list<lead> leadNumbersList = [select MobilePhone from Lead where Status=:statusOfLead and nm_Session__c=:session and nm_Year__c=:integer.valueOf(leadYear)];
for(Lead obj :leadNumbersList)
{
stringOfMobileNumbers = obj.MobilePhone+','+stringOfMobileNumbers;
}
System.debug('stringOfMobileNumbers -->'+stringOfMobileNumbers);
lengthOfCommaSeperatedNumbers = stringOfMobileNumbers.length();
finalString = stringOfMobileNumbers.substring(0,lengthOfCommaSeperatedNumbers-1);
finalString = finalString + defaultNumbersToBeAdded;
System.debug('Final String--->'+finalString+'Message To Be Sent-->'+messageToBeSent);
String response = SMSSenderWebService.sendSMSForNotContactedLead(finalString,messageToBeSent);
System.debug('Response-->'+response);
}
else
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Warning,'Please Mention all the fields For Lead Search'));
return null;
}
return null;
}
public List<SelectOption> getYear()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('2016','2016'));
options.add(new SelectOption('2017','2017'));
options.add(new SelectOption('2018','2018'));
options.add(new SelectOption('2019','2019'));
return options;
}
}
Test Class:-
#isTest
public class nmSendSMSTracker
{
public static Lead obj;
public static nm_Centers__c objLearningCenter;
public static nm_Program__c program;
public static nm_EligiblityCriteria__c eligibility ;
static testMethod void tesMethod()
{
LoadData();
PageReference pg = new PageReference('/apex/nmSendSMS');
Test.setCurrentPage(pg);
Test.StartTest();
nmSendSMS smsSend = new nmSendSMS();
smsSend.getYear();
smsSend.objLead = obj;
smsSend.messageToBeSent ='Hello Vikas';
smsSend.SendSMS();
Test.StopTest();
}
static void LoadData()
{
nm_EscalationMatrix__c objCustomSeetings3 = new nm_EscalationMatrix__c();
objCustomSeetings3.name='0-1 Week';
objCustomSeetings3.nm_LCEscalationTime__c='22:45';
objCustomSeetings3.nm_RemidertoIC__c='22:45';
objCustomSeetings3.nm_HOEscalationTime__c='20:56';
objCustomSeetings3.nm_RemidertoHO__c='22:45';
insert objCustomSeetings3;
nm_EscalationMatrix__c objCustomSeetings = new nm_EscalationMatrix__c();
objCustomSeetings.name='2-4 Months';
objCustomSeetings.nm_LCEscalationTime__c='20:45';
objCustomSeetings.nm_RemidertoIC__c='21:45';
objCustomSeetings.nm_HOEscalationTime__c='20:56';
objCustomSeetings.nm_RemidertoHO__c='21:45';
insert objCustomSeetings;
nm_EscalationMatrix__c objCustomSeetings2 = new nm_EscalationMatrix__c();
objCustomSeetings2.name='3-6 Week';
objCustomSeetings2.nm_LCEscalationTime__c='20:34';
objCustomSeetings2.nm_RemidertoIC__c='21:45';
objCustomSeetings2.nm_HOEscalationTime__c='20:56';
objCustomSeetings2.nm_RemidertoHO__c='21:45';
insert objCustomSeetings2;
nm_Holidays__c objHoliday = new nm_Holidays__c();
objHoliday.Name='Holi';
objHoliday.nm_Date__c=system.today();
insert objHoliday;
// profile objprofile =[SELECT Id FROM Profile WHERE Name='System Administrator'];
user usr = [Select id from user limit 1];
SystemConfiguration__c objSystemConfiguration=new SystemConfiguration__c();
objSystemConfiguration.name='test';
objSystemConfiguration.nm_BusinessHoursStartTime__c='012213';
objSystemConfiguration.nm_BusinessHoursEndTime__c='0234533';
insert objSystemConfiguration;
Recordtype rt=[select id from Recordtype where sobjectType='nm_Centers__c' AND name ='Learning Center'];
objLearningCenter = new nm_Centers__c();
objLearningCenter.RecordTypeID =rt.id;
objLearningCenter.nm_CenterCode__c ='002';
objLearningCenter.nm_CenterCity__c='Delhi';
objLearningCenter.nm_City__c='Delhi';
objLearningCenter.nm_StateProvince__c='Delhi';
objLearningCenter.nm_Street__c='Laxmi Ngar';
objLearningCenter.nm_PostalCode__c='110091';
insert objLearningCenter;
program = new nm_Program__c();
program.nmIsActive__c = true;
program.nm_ProgramCode__c = 'test';
program.nm_ProgramDuration__c= 2.0;
program.nm_ProgramName__c = 'Post grad diploma finance';
program.nm_ProgramValidity__c = 4;
program.nm_TotalSemesters__c = 4;
program.nm_Type__c = 'Post Graduate Diploma Program';
insert program;
eligibility = new nm_EligiblityCriteria__c();
eligibility.Name = 'Bachelors degree';
eligibility.nm_EligiblityCriteria__c = 'bjhwbghbjgw';
eligibility.Experience_Required_In_Year__c= 2;
eligibility.Graduation_Percentage__c = 6;
eligibility.Graduation_Required__c = true;
insert eligibility;
obj = new Lead();
obj.Email='amit.kumar#saasfocus.com';
obj.MobilePhone='8377985721';
obj.FirstName='sandy';
obj.LastName='babar';
obj.nm_BloodGroup__c='B+';
obj.nm_Gender__c='male';
obj.nm_FathersName__c='subhash';
obj.nm_MothersName__c='kalpana';
obj.nm_StateProvince_P__c='maharashtra';
obj.nm_Nationality__c='Indian';
obj.nm_Street_P__c='xyz';
obj.nm_LocalityName__c='mohitep';
obj.nm_SelfLearningMaterial__c='Send to my shipping address';
obj.Status='Cold';
obj.nm_Session__c = 'January';
obj.nm_NameofBoard__c='CBSE';
obj.nm_EligiblityCriteria__c = eligibility.id;
obj.nm_Program__c = program.id;
obj.nm_InformationCenter__c =objLearningCenter.id;
obj.nm_10thPercentage__c=77.00;
obj.nm_NameofBoard__c='ICSC';
obj.nm_YearofCompletion__c='2000';
obj.nm_NameofSchool__c='nutan';
obj.nm_Class12OrDiploma__c='HSC';
obj.nm_NameofBoard12__c='LCSC';
obj.nm_YearofCompletion12__c='2002';
obj.nm_NameofSchool12__c='dfg';
obj.nm_Stream__c='adw';
obj.nm_BachelorsDegreeName__c='gfc';
obj.nm_Specialization__c='gf';
obj.nm_NameofUniversity__c='G K university';
obj.nm_BachelorsDegreePercentage__c=55.00;
obj.nm_GraduationDegreeMode__c='fgc';
obj.nm_YearofCollegeCompletion__c='2006';
obj.LeadSource='Web';
obj.OwnerId=usr.id;
insert obj;
}
}
Error Message:
System.TypeException: Invalid integer:
Class.nmSendSMS.SendSMS: line 37, column 1
Class.nmSendSMSTracker.tesMethod: line 19, column 1
List<Lead> leadNumbersList = [select MobilePhone from Lead where nm_Year__c=:leadYear];
Works for me and I get the correct Lead(s) in the list
I am not able to upload my package because test coverage is below 75%.
How to improve coverage. How to write test methods for triggers.
Please help.
I have tried this code :
This is my controller class:
public class MyController{
public List<Merchandise__c> merch{get;set;}
public Merchandise__c toDelete{get;set;}
public MyController(){
merch = [SELECT ID,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c];
}
public pageReference del(){
string id = Apexpages.currentpage().getParameters().get('merchandiseId');
toDelete = [SELECT Id,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c WHERE Id =: id];
delete toDelete;
return null;
}
public pageReference add(){
Merchandise__c item = new Merchandise__c(
Name = 'Enter Name',
Description__c = 'Enter Description',
Price__c = 0.00,
Total_Inventory__c = 0
);
merch.add(item);
insert item;
return null;
}
public PageReference save(){
string id = Apexpages.currentpage().getParameters().get('merchandiseId');
Merchandise__c toUpdate = [SELECT Name, Description__c, Price__c FROM Merchandise__c WHERE ID =: id];
update toUpdate;
return null;
}
}
I have craeted this Test Class :
#isTest
Public Class demoTest{
static testMethod void checkDatatableData() {
List<Merchandise__c> merch;
Test.startTest();
merch = [SELECT ID,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c];
Test.stopTest();
}
static testMethod void checkAdd() {
Merchandise__c item = new Merchandise__c(
Name = 'Enter Name',
Description__c = 'Enter Description',
Price__c = 0.00,
Total_Inventory__c = 0
);
Test.startTest();
insert item;
System.assertNotEquals(null,item.Id);
List<Merchandise__c> merchItem = [SELECT Id FROM Merchandise__c WHERE Id =: item.Id];
System.assertEquals(1,merchItem.size());
Test.stopTest();
}
static testMethod void checkUpdateDelete() {
Merchandise__c testmerch = new Merchandise__c(
Name = 'NewProduct',
Description__c = 'this is anew product',
Price__c = 20.00,
Total_Inventory__c = 100
);
Test.startTest();
insert testmerch;
system.assertNotEquals(null,testmerch.Id);
testmerch.Price__c = 40.00;
update testmerch;
Merchandise__c updatedmerch = [SELECT Id,Price__c FROM Merchandise__c WHERE Id =: testmerch.Id];
system.assertEquals(40.00,updatedmerch.Price__c);
Merchandise__c toDelete = [SELECT ID FROM Merchandise__c WHERE Id =: testmerch.Id];
system.assertNotEquals(null,toDelete.Id);
delete toDelete;
Test.stopTest();
}
}
Can you please tell me what changes I need to do to improve coverage?
This link should tell you what you need to know.
http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods
Basically you need to replicate the functionality of the trigger in your test methods, so for instance if you have an after update trigger case that runs when it moves from Open to Closed you first need to create a test method for your trigger then within the test method insert a case record for testing, which may also require a contact or an account etc, then you change the value of the case to closed and then run an update method. This is very simplistic but that is the idea. So when writing test classes try to think about what your triggers and classes do and then try to automate what the user would do in your test methods, making sure to cover all your bases including where the piece of apex should fire an exception.
Try to avoid using hard-coded Id's wherever possible.
These links may also help
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_best_practices.htm
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm