I'd like to preface this by saying that I'm very new to writing Apex test Classes, and Apex code in general. I found an Apex class from another post here, and slightly tweaked it for my needs. I've only ever written a single Apex trigger and very simple test class once before.
In summary, the Class takes the Data Category Group, and Data Categories of a Knowledge Article, and places those values into a custom text field on the Knowledge article itself. This is so we can expose them on a page layout.
Code here:
public class ArticleActionDataCategoryUpdate {
// Invoked by process builder
@InvocableMethod
public static void updateArticleTypeForDataCategories(List<Id> articleTypeIds)
{
List<Knowledge__kav> lstArticleType = [SELECT Id, Title, Topics__c FROM Knowledge__kav WHERE Id IN:articleTypeIds
AND PublishStatus = 'draft'];
List<Knowledge__DataCategorySelection> lstDC = [SELECT ParentId, DataCategoryGroupName, DataCategoryName FROM Knowledge__DataCategorySelection
WHERE ParentId IN:articleTypeIds];
Map<Id, String> datacategoryNameMap = new Map<Id, String>();
Map<Id, String> datacategoryParentMap = new Map<Id, String>();
for(Knowledge__DataCategorySelection dcObj:lstDC)
{
if(datacategoryNameMap.containsKey(dcObj.ParentId))
{
String str = datacategoryNameMap.get(dcObj.ParentId);
datacategoryNameMap.put(dcObj.ParentId, str + ', ' + dcObj.DataCategoryName);
datacategoryParentMap.put(dcObj.ParentId, dcObj.DataCategoryGroupName);
}
else
{
datacategoryNameMap.put(dcObj.ParentId,dcObj.DataCategoryName);
datacategoryParentMap.put(dcObj.ParentId,dcObj.DataCategoryGroupName);
}
}
for(Knowledge__kav artObj:lstArticleType)
{
if(datacategoryNameMap.containsKey(artObj.Id))
{
artObj.Topics__c = datacategoryParentMap.get(artObj.Id) +', '+datacategoryNameMap.get(artObj.Id);
}
}
update lstArticleType;
}
}
Test Class:
@isTest
public class TestArticleActionDataCategoryUpdate {
@isTest
public static void testUpdate(){
Knowledge__kav kba = new Knowledge__kav(Title='title1',urlName='test-article');
Knowledge__kav kvb = new Knowledge__kav();
Knowledge__DataCategorySelection dcs = new Knowledge__DataCategorySelection(DataCategoryName='testcat');
dcs.ParentId = kba.Id;
Database.SaveResult res = Database.insert(kba,false);
Database.SaveResult res2 = Database.insert(dcs,false);
Knowledge__DataCategorySelection dcs2 = new Knowledge__DataCategorySelection(ParentId=kba.Id,DataCategoryGroupName='Parent');
List<id> idList = new List<id>();
idList.add(kba.id);
ArticleActionDataCategoryUpdate.updateArticleTypeForDataCategories(idList);
system.assertEquals(kba.Topics__c, kvb.Topics__c);
system.assertEquals('testcat',dcs.DataCategoryName);
system.assertequals('testcat',kba.Topics__c);
system.assertEquals(kba.Topics__c, dcs.DataCategoryGroupName);
}
}
My test class only gives me 47% coverage.
Any guidance or help here, as this is holding up production for us. Thanks