I'm writing a test class to test for a failure, I've already written the test for success and it covers most of the class however, since I have error catches I need to test for success and failure too.

In @testSetup I created Opportunity records already. In my test I need to retrieve the Opportunity id in a set so I can pass it to my class as it expects an incoming set. I wrote this to grab one of the Opps:

Set<Id> oppyIds = (new Map<Id, Opportunity>([SELECT Id FROM Opportunity LIMIT 1])).keyset();

I need to create an OpportunityLineItem record so I went with this:

OpportunityLineItem oliTest = new OpportunityLineItem();
        oliTest.OpportunityId = oppyIds[0];

When I compile I get the error

Expression must be a list type Set

If I change the line to oliTest.OpportunityId = oppyIds[0].id I get:

Illegal assignment from Set to Id

How can I pass the set Id to be the field Id?

1 Answer 1


Sets are not an ordered collection, so you cannot index it in that way. What you'll want to do here is define List<Id> idList = new List<Id>(opptyIds); and then you'll be able to access index 0 with idList[0]

  • 1
    Adding to that, its only Lists and arrays that can be used interchangeably, a privilege that's only possible in SF and not its predecessor, Java.
    – SF Learner
    Dec 1, 2016 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.