Can Data Streams be created via Apex in Tests?
Question
How to Test Data Stream Creation via Apex in a Test Class?
I am trying to create and test Data Streams in Apex within a test class, but I’ve encountered challenges and errors during execution. Here’s the scenario:
In my Apex Controller, I query for Data Streams (and other Data Cloud Metadata Types) and create metadata records based on the query results. This logic works fine in production but is difficult to test.
Here’s what I attempted in my test class:
DataStream ds = new DataStream();
ds.Name = 'Test';
ds.RefreshMode = 'FULL_REFRESH';
ds.RefreshFrequency = 'NONE';
insert ds;
Test.startTest();
processMetadataForDCAlerts.newSetup(formInputs);
Test.stopTest();
The method being tested:
public static Id newSetup(String formInputs) {
List<SObject> metadataToDeploy = new List<SObject>();
Map<String, Object> formValues = (Map<String,Object>) JSON.deserializeUntyped(formInputs);
String typesToDeploy = String.valueOf(formValues.get('typesToDeploy'));
// Deploy Data Stream if the option is selected and there are any records to deploy.
if (typesToDeploy.contains('DataStream')) {
for (DataStream ds : [SELECT Id, Name FROM DataStream]) {
metadataToDeploy.add(ds);
}
}
}
Issue: When attempting to create a Data Stream in the test class, I encounter an Internal Salesforce Error:1908774572-71211 (-1111796172) (-1111796172)
.
The same error occurs when I attempt this via a Flow in debug mode. This suggests it may not be possible to create Data Streams directly in a test class or debug environment.
My Questions:
- Is it possible to create and test Data Streams in Apex within a test class?
- If not, is there a workaround or best practice to test this functionality, especially when the org may not have any metadata pre-configured?
Keywords: Salesforce, Apex, Data Stream, Test Class, Metadata, Internal Server Error, Workaround
Answer
When working with Data Cloud Metadata Types such as DataStream
, there can be challenges in testing operations related to creating or querying these records in Apex test classes. The user shared an issue where their Apex controller queries for existing DataStream
metadata and creates records accordingly. While this works fine in a normal environment, testing it in an Apex test class results in an error.
Here is an example of the code in the controller being tested:
public static Id newSetup(String formInputs) {
List<SObject> metadataToDeploy = new List<SObject>();
Map<String, Object> formValues = (Map<String,Object>) JSON.deserializeUntyped(formInputs);
String typesToDeploy = String.valueOf(formValues.get('typesToDeploy'));
if(typesToDeploy.contains('DataStream')) {
for(DataStream ds : [SELECT Id, Name FROM DataStream]) {
metadataToDeploy.add(ds);
}
}
}
This method, newSetup
, takes a formInputs
string, which is deserialized into a map. It checks if ‘DataStream’ is included in the types to deploy and queries existing DataStream
records. For each DataStream
, it adds it to a list of SObject
metadata to deploy.
And here is the code for the test class:
DataStream ds = new DataStream();
ds.Name = 'Test';
ds.RefreshMode = 'FULL_REFRESH';
ds.RefreshFrequency = 'NONE';
insert ds;
Test.startTest();
processMetadataForDCAlerts.newSetup(formInputs);
Test.stopTest();
In the test class, a DataStream
record is created with mock values and inserted. Then, the newSetup
method is tested by calling it within a Test.startTest()
and Test.stopTest()
block to simulate the process of deploying metadata. However, this results in an internal Salesforce error due to the limitations of metadata operations in test classes.
Solution and Workaround
Unfortunately, Salesforce does not allow the direct creation or insertion of metadata records (such as DataStream
) within test classes. Metadata operations, such as creating or querying DataStream
, are typically not supported in test classes due to the fact that they require access to metadata API, which isn’t available in the test context.
Our Salesforce training in Singapore offers job oriented career building and real-time project based program. Please enroll for demo today!
One possible workaround is to mock the data by creating a custom test setup that simulates the metadata in your tests. This would involve creating fake or dummy records and not interacting directly with Salesforce’s metadata API. Here’s how you might adjust the test class to avoid inserting DataStream
records:
@isTest
private class DataStreamTest {
@isTest static void testNewSetup() {
// Mocking the input
Map<String, Object> formInputs = new Map<String, Object>();
formInputs.put('typesToDeploy', 'DataStream');
// Manually creating a mock DataStream record
List<DataStream> mockDataStreams = new List<DataStream>{
new DataStream(Name = 'Mock Data Stream', RefreshMode = 'FULL_REFRESH', RefreshFrequency = 'NONE')
};
// Mocking the query in the method (instead of actual query)
Test.startTest();
processMetadataForDCAlerts.newSetup(JSON.serialize(formInputs));
Test.stopTest();
}
}
In this test class, a mock formInputs
map is created to simulate input for DataStream
metadata. A mock DataStream
is then manually created instead of querying actual records. This avoids inserting real DataStream
records and ensures the method works without hitting metadata limits during tests.
Another option could be using the Metadata
API directly in tests, but this would require creating a separate testing strategy, including mock responses for those API calls. Keep in mind that Salesforce does not allow real metadata deployments in tests, so these approaches are designed to simulate the behavior.
This solution ensures that the test logic can be validated without requiring actual metadata to be inserted or queried.
Summary
Salesforce does not support direct creation or insertion of metadata records, such as DataStream
, within test classes due to limitations with accessing metadata API in test contexts. In the given scenario, an error occurs when attempting to query and insert DataStream
records during tests.
A workaround involves mocking the data by manually creating mock DataStream
records within the test class, simulating the behavior of metadata deployment without needing actual records. This allows the logic to be tested without triggering metadata-related errors. Real metadata operations are not supported in test classes, so using mock data or alternative approaches, like the Metadata
API with mocked responses, is recommended.
Kick Start Your Journey with Salesforce Learning
Our Salesforce course offers a thorough and engaging learning experience, providing you with the essential skills needed to succeed in the CRM field. The program covers key areas like Salesforce Admin, Developer, and AI, combining detailed theoretical education with hands-on practical experience. Through live projects and assignments, you’ll gain the expertise to solve complex business challenges using Salesforce solutions. Our expert instructors are dedicated to helping you develop both technical skills and industry insights.
In addition to technical training, our Salesforce training in Singapore offers personalized mentorship, guidance on exam preparation, and interview readiness to help you stand out in a competitive job market. You’ll have access to comprehensive study resources, real-world project exposure, and continuous support throughout your learning journey. By the end of the course, you’ll be well-prepared for certification exams and equipped with the practical skills and problem-solving capabilities that employers value. Start your Salesforce career with us and unlock a range of exciting career opportunities!