3

I wrote a test class for my batchable class. It works great but I want to limit the query of the test class only to the test object I have created.

So I have this inside my test method:

String query = 'SELECT Id, Name, ShipmentQuantity__c, CurrentQuantity__c FROM Stock__c WHERE Id =: ' + testStock.Id;

And then my test.StartTest():

system.test.startTest();
Database.executeBatch(new IndependentBatch(query));
system.test.stopTest();

The error I get is

"System.QueryException: Variable does not exist: a0236000001bOXdAAM".

Obviously it sees the ID but I don't understand what the error means. If I erase the Where Id =: ' + testStock.Id; the test runs like a charm.

2

You're mixing up your variables. When you use merge syntax in SOQL, you must use the name of an existing variable in your scope. So if you had a variable called stockId, you could use: 'WHERE Id = :stockId'. You can't do any cross-references, though, so stock.Id cannot be merged in.

However, if you use 'WHERE Id = :'' + stockId, you get a resulting query string of 'WHERE Id = :a0236000001bOXdAAM'. Since you do not have a variable called a0236000001bOXdAAM, you get an error.

| improve this answer | |
  • I didn't think about that. You are correct! Thanks again for clarifying! – Arthlete Mar 1 '16 at 22:33
2

When you use : in a query, it causes the runtime engine to attempt to resolve a variable in the local scope. In other words, it's looking for a variable named a0236000001bOXdAAM. This binding occurs when Database.query, Database.queryCount, or Database.search is called with string parameter.

Instead, you'll need to quote the value correctly:

String query = 'SELECT Id, Name, ShipmentQuantity__c, CurrentQuantity__c FROM Stock__c WHERE Id = \'' + testStock.Id + '\'';
| improve this answer | |

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.