Apex class code is getting highlighted when I tried to check code coverage - salesforce

Test class :
#isTest
public class PriceName_PriceList_test {
#istest static void PriceName_PriceListMethod(){
PriceName_PriceList priceObj = new PriceName_PriceList();
Product_Line_Item__c prl = New Product_Line_Item__c();
prl = [SELECT Product_Name__r.name, List_Price__c FROM Product_Line_Item__c];
prl.Product_Name__r.name = 'testproduct';
prl.List_Price__c = 123;
insert prl;
PriceObj.getdetails();
}
}

You didn't pass the Id to the class. So with a null the query will return 0. But it's interesting, I'd expect you to at least get coverage for line 6...
Change your code to this and run again
insert prl;
PriceObj.drId = prl.Id;
PriceObj.getdetails();
Or make the function accept an Id parameter and call PriceObj.getdetails(prl.Id), no idea what's your use case

Related

Salesforce : Apex test class for the getting trending articles of Knowledge from Community

I need to get trending articles from the community. I created a apex class for that by using ConnectApi.Knowledge.getTrendingArticles(communityId, maxResult).
I need to create a test class for that. I am using test class method provided by Salesforce for that. setTestGetTrendingArticles(communityId, maxResults, result) but I am getting this error "System.AssertException: Assertion Failed: No matching test result found for Knowledge.getTrendingArticles(String communityId, Integer maxResults). Before calling this, call Knowledge.setTestGetTrendingArticles(String communityId, Integer maxResults, ConnectApi.KnowledgeArticleVersionCollection result) to set the expected test result."
public without sharing class ConnectTopicCatalogController {
#AuraEnabled(cacheable=true)
public static List<ConnectApi.KnowledgeArticleVersion> getAllTrendingArticles(){
string commId = [Select Id from Network where Name = 'Customer Community v5'].Id;
ConnectApi.KnowledgeArticleVersionCollection mtCollection = ConnectApi.Knowledge.getTrendingArticles(commId, 12);
System.debug('getAllTrendingTopics '+JSON.serializePretty(mtCollection.items));
List<ConnectApi.KnowledgeArticleVersion> topicList = new List<ConnectApi.KnowledgeArticleVersion>();
for(ConnectApi.KnowledgeArticleVersion mtopic : mtCollection.items)
{
topicList.add(mtopic);
}
return topicList;
}
}
Test class that I am using for this
public class ConnectTopicCatalogControllerTest {
public static final string communityId = [Select Id from Network where Name = 'Customer Community v5'].Id;
#isTest
static void getTrendingArticles(){
ConnectApi.KnowledgeArticleVersionCollection knowledgeResult = new ConnectApi.KnowledgeArticleVersionCollection();
List<ConnectApi.KnowledgeArticleVersion> know = new List<ConnectApi.KnowledgeArticleVersion>();
know.add(new ConnectApi.KnowledgeArticleVersion());
know.add(new ConnectApi.KnowledgeArticleVersion());
system.debug('know '+know);
knowledgeResult.items = know;
// Set the test data
ConnectApi.Knowledge.setTestGetTrendingArticles(null, 12, knowledgeResult);
List<ConnectApi.KnowledgeArticleVersion> res = ConnectTopicCatalogController.getAllTrendingArticles();
// The method returns the test page, which we know has two items in it.
Test.startTest();
System.assertEquals(12, res.size());
Test.stopTest();
}
}
I need help to solve the test class
Thanks.
Your controller expects the articles to be inside the 'Customer Community v5' community, but you are passing the communityId parameter as null to the setTestGetTrendingArticles method.

Salesforce Test Class - System.NullPointerException: Attempt to de-reference a null object

Salesforce Test Class - Facing - System.NullPointerException: Attempt to de-reference a null object Error while trying to Run Test Class
APEX class
public class NewAccountCreation {
public Account account{get;set;}
public void save(){
Account acc = new Account();
// User enter values in vf page and we are capturing and creating account
acc.name = account.Name;
//acc.address = account.adress;
Insert acc;
}
}
Test Class
#isTest
public class TestNewAccountCreation {
#isTest static void TestNewAccountCreationMethod(){
NewAccountCreation testAccount = new NewAccountCreation ();
Account acc = new Account(Name='TestAcct');
Insert acc;
system.debug(''+acc);
testAccount.save();
System.assert([Select Id From Account].size()==1);
}
}
Error:
System.NullPointerException: Attempt to de-reference a null object
StackTrace:
Class.NewAccountCreation.save: line 6, column 1
Class.TestNewAccountCreation.TestNewAccountCreationMethod: line 9, column 1
You never set testAccount.account, so it's null. You do need to populate this variable, and you do not need to create and insert an Account in your test code. In fact, doing so will cause your assertion to fail.

Unit Test Case For Spring jdbc template for RowMapper

I know it is not a good thing write a unit test for mapper or get set but, it is what it is, so I am stucked how to do unit test for mappers;
StudentGroupList below;
#Getter
#Setter
public class StudentGroupList {
private String studentId;
}
StudentGroupListRowMapper below;
public class StudentGroupListRowMapper implements RowMapper<StudentGroupList> {
#Override
public StudentGroupList mapRow(Resultset rs, int rowNum) throws SQLException {
StudentGroupList studentGroupList = new StudentGroupList();
studentGroupList.setStudentId(rs.getString("student_id"));
return studentGroupList;
}
}
I have tried below, but jococo coverage test did not coverage anything
public class TaskGroupListRowMapperTest {
private ResultSet resultSet;
private StudentGroupList studentGroupList;
#Before
public void setUp() {
resultSet = mock(ResultSet.class);
studentGroupList = mock(StudentGroupList.class);
}
#Test
public void testStudentGroupListMapper() throws SQLException {
when(resultSet.getString("student_id"))
.thenReturn(studentGroupList.getStudentID());
assertTrue(studentGroupList.getStudentId(), true);
}
}
İt says exception; thenReturn() may be missing.
Take it easy, we were all there in the past and try to understand what a unit test is supposed to do.
You don't unit test everything just for the sake of unit test coverage. When you have a framework callback like RowMapper, it is one of those cases. Your StudentGroupListRowMapper is very simple, so an integration test for your Dao will cover it. Anyway, you want to unit test so just think of it as a simple class and let's go through the steps.
You want to create the instance of the class you want to test and also provide mock dependencies for any services it calls. Luckily your StudentGroupListRowMapper does not call anything. Since the method you want to test is StudentGroupList mapRow(Resultset rs, int rowNum), you have to decide if you can provide a Resultset and a rowNum. Since Resultset is not something you create, your provide a mock for that
Resultset inputRs = mock(Resultset.class);
int rowNum = 1;
Now when your method executes, it is going call inputRs.getString("student_id") to get student id but it is mock and it doesn't know what to return so you have to tell your mock what to do when inputRs.getString("student_id") is called
when(inputRs.getString("student_id")).thenReturn("sutdent-id-1");
Now you know your expected StudentGroupList should be created with "sutdent-id-1" and should be returned from the method.
assertEquals(resultedStudentGroupList.getStudentId(),"sutdent-id-1");
Lets combine all of them together.
public class StudentGroupListRowMapperTest {
StudentGroupListRowMapper mapper = new StudentGroupListRowMapper();
#Test
public void testMapRow() {
Resultset inputRs = mock(Resultset.class);
int rowNum = 1;
when(inputRs.getString("student_id")).thenReturn("sutdent-id-1");
StudentGroupList result = mapper.mapRow(inputRs, rowNum);
assertEquals(result.getStudentId(), "sutdent-id-1");
}
}

How to get query covered in apex test class for salesforce

I'm having a tough time trying to get all code covered in my test class for an apex class.
Apex class:
public with sharing class myclass {
**public List<CustomObject1> listvar {get;set;}**
public myclass(ApexPages.StandardController sc){
CustomObject2 var = [SELECT Id, Field1__c FROM CustomObject2 WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
**listvar = [SELECT Id,Name,Field1__c,Field2__c,Field3__c,Field4__c,Field5__c,CreatedDate,CreatedById FROM CustomObject1 WHERE Field2__c = :var.Field1__c ORDER BY CreatedDate DESC];**
}
}
Test Class:
#isTest
public class myclass_Test {
static testmethod void dosomething(){
Account a = new Account();
a.Name = 'Test acct';
insert a;
CustomObject4__c v = new CustomObject4__c();
v.Field1__c = '123 ABC';
v.Name = 'test name';
v.Field2__c = True;
v.Account__c = a.Id;
insert v;
... more record creates including ones for the object being queried...
PageReference pageref = Page.myVFpage;
Test.setCurrentPageReference(pageref);
ApexPages.StandardController sc = new ApexPages.StandardController(v);
myclass myPageCon = new myclass(sc);
}
}
I've tried creating a new list for the underneath the last line in the test class and populating the list, but I cannot get 100% code coverage. I marked the lines that I'm not getting any coverage from the test class with. Any suggestions?
You should put some asserts into your test Class. Something like
System.assertEquals(5, yourListsize)
I figured out that the listvar list for CustomObject1 wasn't getting populated because an Id wasn't being passed to var for CustomObject2. In the test class I had to put the record Id using ApexPages.currentPage().getParameters().put('Id', something.id);
with the Id for the record created in the test class for that object. Thanks anyways guys :-)

Insert CSV using Apex Batch Class Salesforce for OpportunityLineItem

I want to add a button to my opportunity header record that is called Insert Products. This will send the opportunity ID to a visualforce page which will have a select file button and an insert button that will loop through the CSV and insert the records to the related opportunity.
This is for non technical users so using Data loader is not an option.
I got this working using standard apex class however hit a limit when i load over 1,000 records (which would happen regularly).
I need to convert this to a batch process however am not sure how to do this.
Any one able to point me in the right direction? I understand a batch should have a start, execute and finish. However i am not sure where i should split the csv and where to read and load?
I found this link which i could not work out how to translate into my requirements: http://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/
Here is the code i have for the standard apex class which works.
public class importOppLinesController {
public List<OpportunityLineItem> oLiObj {get;set;}
public String recOppId {
get;
// *** setter is NOT being called ***
set {
recOppId = value;
System.debug('value: '+value);
}
}
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<OpportunityLineItem> oppLine{get;set;}
public importOppLinesController(){
csvFileLines = new String[]{};
oppLine = New List<OpportunityLineItem>();
}
public void importCSVFile(){
PricebookEntry pbeId;
String unitPrice = '';
try{
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
OpportunityLineItem oLiObj = new OpportunityLineItem() ;
string[] csvRecordData = csvFileLines[i].split(',');
String pbeCode = csvRecordData[0];
pbeId = [SELECT Id FROM PricebookEntry WHERE ProductCode = :pbeCode AND Pricebook2Id = 'xxxx HardCodedValue xxxx'][0];
oLiObj.PricebookEntryId = pbeId.Id;
oLiObj.Quantity = Decimal.valueOf(csvRecordData[1]) ;
unitPrice = String.valueOf(csvRecordData[2]);
oLiObj.UnitPrice = Decimal.valueOf(unitPrice);
oLiObj.OpportunityId = 'recOppId';;
insert (oLiObj);
}
}
catch (Exception e)
{
ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e + ' - ' + unitPrice);
ApexPages.addMessage(errorMessage);
}
}
}
First problem that I can sense is that the insert DML statement is inside FOR-loop. Can you put the new "oLiObj" into a List that is declared before the FOR-loop starts and then try inserting the list after the FOR-loop ?
It should bring some more sanity in your code.

Resources