My test class currently includes the code from here only, with the exception described below: https://developer.salesforce.com/page/Apex_Testing_with_RunAs

I've added this line of code just above the class: @IsTest(SeeAllData=true)

When I run this test I receive the below error:

"System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, You're creating a duplicate contact record. We recommend selecting the "Contacts" tab, performing a search for the existing record instead."

Removing the (SeeAllData=true) part makes the tests all pass. The problem is that I need SeeAllData in there because I also need to add a bit of code to this class that will call a controller method which uses portions of the ConnectAPI that require SeeAllData=true.

So what's going on here? Is it not possible to test code connecting calls to the ConnectAPI which require SeeAllData=true?

  • As an alternative you can use Test.istestrunning() method to skip some code execution during test run or use static boolean to skip some code .You can use two different methods and during each test run you can flip boolean . Dec 20, 2015 at 3:50
  • That's one of the weird things here. I tried surrounding the Contact creation code with a try/catch and simply swallowed the error, Finally I did a select to get the created contact (the one that didn't throw the error, assuming my code was somehow running twice). Turns out no contact was inserted! What's up with that?
    – SF1Dev
    Dec 20, 2015 at 15:16

1 Answer 1


As per Salesforce documentation you need seeAllData=True when testing methods for ConnectAPI. We don't have much control for that.

However to solve your issue, you can attach timestamps to unique fields, while populating them. I use this as a best practice to duplicate errors.

This is what I will do to modify your code:

Account a;
Contact c;
System.runAs(userWithRole) {

    a = new Account(name = 'TEST ACCOUNT'+system.now());

    c = new Contact(AccountId = a.id, lastname = 'lastname'+system.now());

  • Trying this I receive the exact same error as I noted above. I had previously tried something simliar in which I used some randomized text as the last name, thinking that somehow my code was being executed twice but that appears not to be the case.
    – SF1Dev
    Dec 20, 2015 at 17:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .