[SalesForce] Apex Test Failure – System.QueryException: List has no rows for assignment to SObject

I am receiving an apex test error – the error message is:

System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.BillingScheduleTest.TestBillingSchedule2: line 108, column 1

When I view the code in the developer console – line 108 code is the below:

Asset objAS = [Select Id,Contract__c,Name  From Asset Where Name= 'TestAsset' Limit 1];

The whole code can be found at: https://gist.github.com/JennSchnell/1fe9ab2fc2288ad5077baa15ae61ddfa

Still learning a lot of this stuff, but is the error telling me that I don't have an Asset with the name "TestAsset"?

Best Answer

is the error telling me that I don't have an Asset with the name "TestAsset"?

Precisely. The "List has no rows for assignment" means that you tried to assign the result of a query that returned no records to a variable.

If you get a "List has more than 1 row for assignment to SObject" error it would mean the opposite: you got more than one record in your query, and you are trying to assign it to a single instance in your code. In this case you need to either refine your query to get just one record or change your variable type to a list.

Edit:

So, after reading your code, some things come to my mind:

  1. On the first line you have seeAlldata=true in your class. This means that when the test is run, it will be able to read the data in your organization. No big deal, actually, but you might not need this, see below.
  2. Lines 3 to 81 are basically for setting up some test data (which would make the seeAllData=true useless.
  3. TestBillingSchedule1 and TestBillingSchedule2 are methods that will be using the test data created previously. If they are failing then you need to fix whatever is causing the error (in this case, the Asset is missing from the test data).
  4. If the AssetTriggerHandlerTest class is also failing, you might want to check it before, since it is testing a trigger. The trigger behaviour will likely affect other tests, like the first one you posted.
  5. See the introduction to test methods.
Related Topic