[SalesForce] System.DmlException: Insert failed

I am having trouble with one of my test classes (PortalControllerTest) which keeps failing validation.

This is the error I receive:

    System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateOpportunity: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.CreateOpportunity: line 12, column 1: []

PortalController Apex:

static testMethod void myTest() {
User usr = [Select Id,ContactId From User where ContactId != null AND IsActive = true limit 1];
Service_Order__c sOrder;
System.RunAs(usr)
{
    sOrder = new Service_Order__c();
    sOrder.Name ='SO01';
    sOrder.building__c = 'LHR';
    sOrder.Project_Deadline__c = system.today();
    sOrder.Accept_Terms_Conditions__c = true;
    insert sOrder;

}

CreateOpportunity Trigger:

    trigger CreateOpportunity on Service_Order__c (before insert,after insert){

        Id UserId = UserInfo.getUserId();

        User user = [select AccountId, ContactId from User where id=:UserId];

        Account account = [select building__c,LHR__c, ABZ__c, SOU__c, GLA__c, STN__c, EDI__c,OwnerId from account where id=:user.AccountId];

        Set<String> buildingList = new Set<String>();
        if(account.LHR__c) buildingList.add('LHR');
        if(account.EDI__c) buildingList.add('EDI');
        if(account.GLA__c) buildingList.add

('GLA');    
    if(account.SOU__c) buildingList.add('SOU');
    if(account.STN__c) buildingList.add('STN');
    if(account.ABZ__c) buildingList.add('ABZ');    

    Opportunity opp = new Opportunity();
    opp.StageName = '04 - Qualification Prebid';


    Service_Order__c ServiceOrder = trigger.new[0];

...

From the error message I see it has some kind of relation to a trigger called CreateOpportunity.
I know there are definetly records in the Users table.

Best Answer

Several suggestions:

1). If you are trying to use existing data in your unit test class, add @istest(seealldata=true) in the top of the test class (may be you already have this in your code).

@istest(seealldata=true)
public class your_testclass{
   // your code
}


2). Try to assign your query results into List instead of to a single instance.

List<User> users = [select AccountId, ContactId from User where id=:UserId];

and then work with that list,

if(users != null && users.size() > 0){
  List<Account> accounts = [select building__c,LHR__c, ABZ__c, SOU__c, GLA__c, STN__c, EDI__c,OwnerId from account where id=:user[0].AccountId];
}


3). If you much sure that there is one record and need to assign into single instance, try

User user = [select AccountId, ContactId from User where id=:UserId][0];
Account account = [select building__c,LHR__c, ABZ__c, SOU__c, GLA__c, STN__c, EDI__c,OwnerId from account where id=:user.AccountId][0];

(but I don't like this method since it intend to throw exceptions).