[SalesForce] SOQL not returning results in Test Apex class

I am having a simple test class as below

 @isTest
public class codecovertess {

    @isTest
     public static void test1()
    {
        Account a = new Account();
        a.Name='testppcodecove';
        Account x = [select id,name from Account LIMIT 1];
        System.debug('x value==='+x.Name);
        ApexPages.StandardController stdController  = new ApexPages.StandardController(x);
        tess t = new tess(stdController);
        t.getGreeting();
        String vartest=t.testvar;
        System.assertEquals('a', 'a');
    }
}

When i am using this test class i am getting an error as

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

But when i am removing @isTest and running like a normal Apex class it is working fine,i am confused ,shouldnt we use SOQL in Test class.Can anyone please help me understand why i am not able to run it in Test class.

Thanks in Advance.

Best Answer

This is because you need to first insert the account record. Check my comments.

Account a = new Account();
a.Name='testppcodecove';
insert a/insert here
Account x = [select id,name from Account LIMIT 1];
System.debug('x value==='+x.Name);
ApexPages.StandardController stdController  = new ApexPages.StandardController(x);
tess t = new tess(stdController);
t.getGreeting();
String vartest=t.testvar;
System.assertEquals('a', 'a'); //Also this assert is not useful you can check better condition here

Also you should check Apex Testing Trailhead module to get better understanding.

Related Topic