+1 vote
166 views
by (163k points)

I'* using the Product object and store the product sku within the StockKeepingUnit field. According to the Winter 18 release notes, this field is considered unique, which is totally fine and expected for me.

However, when I use apex testing classes, my product2 testing records that I create for testing are conflicting with the product2 records already part of my Salesforce instance. This doesn't make a lot of sense to me because I am not using seeAllData=true in my testing classes, those records in my Salesforce instance should not get into conflict with my testing records.

Here is the error message I get when I try to insert a test record that has a product sku equal to a product2 record already part of my Salesforce instance. System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, A Product with this SKU already exists.: [StockKeepingUnit]

I've tested it in a brand new scratch org to the same result.

HOW TO REPRODUCE:

I've added a new product2 record through the dev console

Product2 testExistingProduct = new Product2(StockKeepingUnit='60235280574',Name='Fake Name',IsActive=true);
insert testExistingProduct;

Here is the testing class

@isTest
private class TestDuplicateSku {
    @testSetup static void setup() {
        Product2 testExistingProduct = new Product2(StockKeepingUnit='60235280574',Name='Fake Name',IsActive=true);
        insert testExistingProduct;
    }
    
    @isTest static void   TestBasicProductAddProperties() {
        Test.startTest();
        Test.stopTest();
        Product2 updatedProduct = [select id,StockKeepingUnit from Product2 where StockKeepingUnit='60235280574'];
        System.assertEquals('60235280574',updatedProduct.StockKeepingUnit,
        'Product sku should be defined');
    }
}

Error message:

TestDuplicateSku.TestBasicProductAddProperties System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, A Product with this SKU already exists.: [StockKeepingUnit]

force-app/main/default/classes/TestDuplicateSku.cls:5:1

1 Answer

+1 vote
by (163k points)
 
Best answer

I had the exact same problem, even flagging (SeeAllData=false) explicitly.

It appears that even in test cases SF validates the SKU across all product records.

I got around it in my test classes by ensuring the product SKU was guaranteed to be unique & not match anything in an existing product record (in my case I appended 'SF-UNITTEST-' to all SKUs in my spoofed http requests).

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
...