New answers tagged

-1

you have to remove the @isTest from your method; otherwise, the changes inside your batch will not be committed. Of course, when the test ends, the rollback is done automatically: static void test_schedulable(){ ... } you should not use testmethod in this case as well.


1

System.runAs(new User(Id = guID)){ You're not actually inserting a User, you're only creating a new instance of one. If you want to be able to query for that user they need to be inserted.


1

You're only setting a userId if ipAddress.size() > 0, but you're not inserting any Black_IP___c records in your test. Apex Test methods only have access to data created in the same method or data created in a method in the same test class that's annotated with @TestSetup. If you change the annotation for your test method, to @isTest(SeeAllData=true), you'...


1

If you want to mock a CronTrigger, you can use the JSON serialize/deserialize approach (see sfdcfox answer which is concise and works nicely for simple mocking) My favorite library for read-only fields is SObjectFabricator by @mattaddy CronTrigger[] mockCronTriggers = new List<CronTrigger> { (CronTrigger) new sfab_FabricatedSObject(...


1

The issue was that the CreateCommunityUser class was being invoked by a flow when the new contact was created, and then invoked again when I called CreateCommunityUser.createExternalUser(contacts);


1

Arguably, I'd optimize away the bits that really don't matter: @TestVisible private void rescheduleJob(CronTrigger me, ISchedulable item, MySchedulableContext myCtx) { try { System.abortJob(me.Id); } catch(Exception e) { System.debug('Could not abort the job'); } String newTrigger = item.getNextTriggerString(myCtx); if ...


1

Realistically, the only real option is to reduce/eliminate redundant DML and SOQL operations as much as possible. This includes using @testSetup annotations to create records, dependency injection when possible to create "fake" records when possible, and creating a trigger framework that can enable/disable triggers in memory without the use of ...


0

One important note is that we cannot perform DMLs on setup and non-setup objects in the same transaction. Workaround is that you can use System.RunAs with different users to separate out transactions for setup and non-setup objects. Try to insert Contact and Invoice inside System.runAs(currentUser){} block as show below: System.runAs(currentUser) { ...


0

Had the same issue; found wa: changing default org to other, and changing again to the valid sfdx force:config:set defaultusername=<other_connected_org> sfdx force:config:set defaultusername=<org_where_you_want_to_run_tests> running the tests after that, did the trick


3

In general, triggers (and workflow, process builder, validation rules, and flows) cannot be turned off. We can use things like Custom Metadata Types and Custom Settings to provide a way for us to turn those things on and off at will, but the point is that it's something that you need to add into your code (and it's generally easier to add it the earlier you ...


1

You can only skip those triggers if they have some built in functionalities to do so (e.g. built-in flags, switches to deactivate them or a trigger framework was used which supports it)


2

While there is a great deal of missing information here (how is this code invoked? what is the other invocable method?), there is one clear problem: The test data you are generating does not match the entry expectations for two of your branches. You create a record List <Patient_Event__c> SEevent = new list<Patient_Event__c>(); SEevent[0]...


1

The golden rule of unit testing is you only get coverage for code that is executed as part of a unit test. With unit testing, you are the one responsible for making sure that the correct data is in place to get you to execute the code path that you want coverage for. In many cases, you'll want to have multiple test methods. One test can create test data that ...


2

Static variables set in an @testSetup method are always cleared before running individual test methods. It's annoying, but that's the direction that Salesforce took. The way I get around this in my tests is to have an unannotated static method to do any common querying/variable setup example @isTest private class MyTest{ static Map<Id, Account> ...


0

Your method is not static, so you need to create an instance of your class in the unit test. EmailDistributerTemplate controller = new EmailDistributerTemplate(); controller.accountId = acc.Id; Account[] results = EmailDistributerTemplate.getLocation(); This should be done after creating the test data (the code you've already written).


1

you don't call the method EmailDistributerTemplate.getLocation Thats why you don't get coverage for it.


0

You need to simulate the way E2C works under the covers. It looks like you don't care whether the email has attachments. The running user should be the user defined in Support Settings (Case Automation user) Insert Case(s) using the same field values that your E2C setup has configured (Origin, Recordtype, Priority, Owner) If important to you, you can coerce ...


1

I see you haven't created test data for the object Priority_List_Distribution__c in your test class. Adding following lines of code in the test class, would cover the class fully: Priority_List_Distribution__c PrLDistri = new Priority_List_Distribution__c(); insert PrLDistri; Result with simple example: See similar thread and discussion


2

System.runAs only runs in actual unit tests. Execute Anonymous is not a unit test context; any changes you make in Execute Anonymous successfully will save. If you want to run tests, you need to do a metadata deployment. If you don't want to actually save the changes, use the -c (check only) deployment mode. However, metadata deployments are still always in ...


1

Based on its documentation, the force apex command executes Anonymous Apex, not an Apex unit test. The runAs() construct, along with Test.startTest() and Test.stopTest(), is available only in the context of an Apex unit test. Note that executing Anonymous Apex also does not save anything - it is not a development activity. The Force CLI is an open source ...


0

As of Summer ’20 and later, only authenticated internal and external users can access this object. A queue is a Group whose Type is Queue. To create a Group, you must have the Manage Users permission. Refer this for more details


0

You do need to specify a SetupOwnerId. I'd recommend the more usual method of getting the (optional) default value and using upsert. // testMethod is deprecated @isTest static void test2(){ HttpRequest req = new HttpRequest(); // SetupOwnerId will be set for you here. Developer_Monitoring__c dm = Developer_Monitoring__c.getOrgDefaults(); dm....


1

Your code can throw a "No rows returned" QueryException, because you're filtering to see if the city is not blank/null. Instead, consider code like this: @AuraEnabled(cacheable=true) public static String getCity() { for(User currentUser: [SELECT City FROM User WHERE Id = :UserInfo.getUserId() AND City != null]) { return currentUser.City;...


0

Instead of "passing in" a runAs, which would burn a lot of unnecessary DML statements, just wrap the setup parts in a runAs: @TestSetup static void dataSetup(){ Id rtVBAccount = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Vendor_Builder').getRecordTypeId(); Profile rewProfile = [SELECT id,Name,...


0

Personally, I'd say, don't worry about it. As I stated before, 100% coverage may be impossible in some cases, and 90%+ should be acceptable in most cases. That said, in your specific case, you could pass in an invalid url-encoded string. try { ClassName myController = new ClassName(); myController.uploadResume('%a',null); System.assert(false, 'Expected ...


2

All apex code, both production and tests, must appear in a "classes" folder in one of your "source" or "mdapi" structured projects. On the assumption you're using a "source" structure and that you're using conventional organization where you have "force-app/main/default" as your directory structure, the Apex ....


2

Your Apex unit tests have no access to data outside the test context unless @seeAllData=true is specified (which you should almost never do). Even if you have visibility to the data through that annotation, changes made to data during test context is always rolled back at the end of the test. Running a test should never impact your real org data. If you were ...


1

The issue is that the PushTopic name must be unique. Could you please try to generate the random name and then set that as a name in test class context. Sample code to generate random string. Integer len = 20; Blob blobKey = crypto.generateAesKey(128); String key = EncodingUtil.convertToHex(blobKey); String Name = key.substring(0,len);


Top 50 recent answers are included