0

enter image description hereHere this is the class:

public class relatedList 
{

    public account acc{set;get;}
    public contact con{set;get;}    
    public string accname{set;get;}
    public void getdata() {
      acc=[select name,id from account where name=:accname];
      con=[select id,name,title,email,phone from contact where account.id=:acc.id limit 1];
    }

}

Here is Test Class which covers only 83% why not 100%? Showing error like list has no rows. Help me to resolve this.

@isTest

public class relatedList_TC

{

    static testMethod void testMthd()
    {
        relatedList rl=new relatedList();
        account a=new account(name='xxx');
        contact c=new contact(lastname='yyy',accountid=a.id);
        rl.getData();
    }
}

2 Answers 2

0

As the SOQL is filtering by accname, you need to set that field in your unit test. You also need to insert the objects in the test so they can be queried. So overall:

static testMethod void testMthd()
{
    account a=new account(name='xxx');
    insert a;
    contact c=new contact(lastname='yyy',accountid=a.id);
    insert c;

    relatedList rl=new relatedList();
    rl.accname = 'xxx';
    rl.getData();
    System.assertEquals(a.Id, rl.acc.Id);
    System.assertEquals(c.Id, rl.con.Id);
}

You should also add a "limit 1" to the Account query in your relatedList class because in production there could easily be multiple Accounts of the same name.

7
  • Thank you for replay but accname is not a variable in test class,one more thing problem @Contact list
    – Krish25
    Commented Dec 6, 2014 at 11:38
  • @Krish25 In your test method set rl.accname = 'xxx';.
    – AslamK
    Commented Dec 6, 2014 at 11:55
  • @Krish25 By having rl. in front of accname the test code is setting a field in an instance of relatedList. And you are right that isn't enough change to get your test to work: the Account and Contact need to be inserted into the database as well as created in memory. See the updated code in the answer.
    – Keith C
    Commented Dec 6, 2014 at 14:07
  • Compile Error: Variable does not exist: r1.accname ,i am getting this error.
    – Krish25
    Commented Dec 7, 2014 at 2:45
  • @Krish25 - it is rl.accname not r1.accname (letter l not number 1)
    – Eric
    Commented Dec 7, 2014 at 4:11
0

You need to insert your records within the test class, and then they will be available to the SOQL query:

static testMethod void testMthd()
{
    relatedList rl=new relatedList();
    account a=new account(name='xxx');
    insert a;

    contact c=new contact(lastname='yyy',accountid=a.id);
    insert c;

    rl.getData();
}
1
  • Still same coverage 83%,not covering Contact query.help me to cover that query.
    – Krish25
    Commented Dec 7, 2014 at 2:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .