I want to test my method and I have this error:
FATAL_ERROR|System.LimitException: Too many SOQL queries: 201
Class.PatchPanelTriggerClass.deleteDuplicates: line 202, column 1
Class.PatchPanelTriggerClassTestBatch.execute: line 19, column 1
I know that I have method that runs SOQL in for loop (in batch) but I don't know how to fix it.
This is my method to test:
public static void deleteDuplicates(String patchPanelName) {
patchPanelName = patchPanelName + '%';
Map<String, Interface__c> records = new Map<String, Interface__c>();
List<Interface__c> duplicates = new List<Interface__c>();
// change it for all PatchPanels which starts with certain patchPanelName
for (Interface__c record : [SELECT Name, Status__c FROM Interface__c where Name like :patchPanelName limit 50000]) { // Class.PatchPanelTriggerClass.deleteDuplicates: line 202, column 1
// take duplicates to delete
Interface__c temp = records.put(record.Name, record);
// put duplicates to remove them
if (temp != null && temp.Status__c != 'Live') {
duplicates.add(temp);
}
}
delete duplicates;
}
This is my batch:
global with sharing class PatchPanelTriggerClassTestBatch implements Database.batchable<SObject>, Database.Stateful {
public Boolean flag = false;
@TestVisible static Boolean flagForTest = false;
global void execute(Database.BatchableContext param1, List<Patch_Panel__c> param2) {
flag = true;
for (Patch_Panel__c p : param2) {
PatchPanelTriggerClass.deleteDuplicates(p.Name); // Class.PatchPanelTriggerClassTestBatch.execute: line 19, column 1
List<Interface__c> records = [SELECT Name, Id, Status__c, Port_No__c, Rack__c, Show_in_Customer_Portal__c FROM Interface__c where Name LIKE :p.Name]; // Too many SOQL queries: 201
if (thereAreNoDuplicates(records) == false) {
flag = false;
}
}
}
// just a method which don't do any SOQL
private static Boolean thereAreNoDuplicates(List<Interface__c> records) {
Set<String> setOfInterfaces = new Set<String>();
for (Interface__c i : records) {
if (setOfInterfaces.contains(i.Name)) {
return false;
}
setOfInterfaces.add(i.Name);
}
return true;
}
global void finish(Database.BatchableContext param1) {
flagForTest = flag;
}
global Database.QueryLocator start(Database.BatchableContext param1) {
String s = 'select Name, Total_No_of_Ports__c from Patch_Panel__c limit 160'; // todo1
return Database.getQueryLocator(s);
}
}
How to fix it?