function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
belabela 

can any one help to write test class for below code.

I wrote a class when record is inserted it is redirected to another page and should display that record as output field.I wrote a test class for first class,but i dont know how to write test class for pagereference and 2nd class.Please help me

class 1(save record)
-----------
public with sharing class saveInputController {
public string positionname{set;get;}
   
   
    public PageReference saveposition() {
    position__c p=new position__c();
     p.name=positionname;
     insert p;
     PageReference posPage = new PageReference('https://c.ap2.visual.force.com/apex/showinput?id=' + p.name);//I didnt covered this in test class .
     posPage.setRedirect(true);
     return posPage;
    }
}
testclass for class one
------------------------------------

@isTest
public class testsaveInputController{

public static testmethod void v1 (){
position__c p= new Position__c(name='maha');
insert p;
position__c p1= new Position__c(name='maha1');
insert p1;
position__c p2= new Position__c(name='maha2');
insert p2;
Test.startTest();
saveInputController sic=new saveInputController ();
PageReference myVfPage =sic.saveposition();
Test.stopTest();
System.assertEquals('maha', myVfPage );
}
}



class2(display as outfield)(I am not knowing how to write testclass for this because of page reference)
--------------------------------------
public with sharing class showinputcontroller {
public List<position__c> p{get;set;}

public showinputcontroller(){
p=[select name from position__c where name like :ApexPages.currentPage().getParameters().get('id') limit 5];
}

}

Thanks,
Mahanandeesh.
Best Answer chosen by bela
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
@isTest
public class showinputcontrollerTest{

	public static testmethod void TestMethod1()
	{
		position__c p= new Position__c(name='maha');
		insert p;
		Test.startTest();

			PageReference pageRef = Page.showinput; // Add your VF page Name here
			//pageRef.getParameters().put('id', String.valueOf(p.Id));
			pageRef.getParameters().put('id', 'maha');
			Test.setCurrentPage(pageRef);
			showinputcontroller sic=new showinputcontroller ();
			System.assertEquals(1, sic.p.size());
		
		Test.stopTest();
	}
}

Please try below test class for "saveInputController"
@isTest
public class testsaveInputController{

	public static testmethod void TestMethod1()
	{
		
		Test.startTest();
			
			saveInputController sic=new saveInputController ();
			sic.positionname ='maha'
			PageReference myVfPage =sic.saveposition();
			System.assertNotEquals(null,pageRef);
			
		Test.stopTest();
	}
}
Please let us know if this will help you

 

All Answers

Mustafa JhabuawalaMustafa Jhabuawala
You need to write a different test class for your showinputcontroller class and then just set the parameter in the test method as show below
ApexPages.currentPage().getParameters().put('id','144');
Then just assert your result that is stored in which is your List<poistion__c> object and you are done :)

Mark this as a solution if you find this helpful.
Amit Chaudhary 8Amit Chaudhary 8

1st Test class.
 
@isTest
public class testsaveInputController{

	public static testmethod void TestMethod1()
	{
		
		Test.startTest();
			
			saveInputController sic=new saveInputController ();
			sic.positionname ='maha'
			PageReference myVfPage =sic.saveposition();
		
		Test.stopTest();
	}
}

2nd Test Class.
 
@isTest
public class showinputcontrollerTest{

	public static testmethod void TestMethod1()
	{
		position__c p= new Position__c(name='maha');
		insert p;

		Test.startTest();
			
			PageReference pageRef = Page.showinput; // Add your VF page Name here
			pageRef.getParameters().put('id', String.valueOf(p.Id));
			Test.setCurrentPage(pageRef);
  
			showinputcontroller sic=new showinputcontroller ();
			sic.positionname ='maha'
		
		Test.stopTest();
	}
}


Please check below post for test classes. I hope that will help you
1) http://amitsalesforce.blogspot.in/search/label/Test%20Class
2) http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks
Amit Chaudhary
belabela
Hi Amit,
Thanks for the reply,I able to understand testclasses,but I have few doubts regarding above testclass. 
1.can u please tell me what is the use of below code for test class 2.As positionname is in saveinputcontroller it is showing error.can we take reference of one class in another?
showinputcontroller sic=new showinputcontroller ();
            sic.positionname ='maha';

2.If you dont mind,Can you please write system.assertequals for above test cases ,so that i can get what's happening.


Thanks,
B.Mahanandeesh
belabela
Hi Amit,
Thank you so much Amit for your help.
1.for showinputcontrollerTest :I am getting Error: Compile Error: Method does not exist or incorrect signature: [showinputcontroller].size() at line 14 column 36

2.System.assertEquals(1, sic.size()):I have seen in many testclasses many of them are using size method in assertion,actually what its returning?what is 1 here, is it a one record which is displayed? can you please explain?

Thanks and Regards
B.Mahanandeesh
Amit Chaudhary 8Amit Chaudhary 8
PLease try below test class for "showinputcontroller"
@isTest
public class showinputcontrollerTest{

	public static testmethod void TestMethod1()
	{
		position__c p= new Position__c(name='maha');
		insert p;
		Test.startTest();

			PageReference pageRef = Page.showinput; // Add your VF page Name here
			pageRef.getParameters().put('id', String.valueOf(p.Id));
			Test.setCurrentPage(pageRef);
			showinputcontroller sic=new showinputcontroller ();
			System.assertEquals(1, sic.p.size());
		
		Test.stopTest();
	}
}
In below line we are checking size of P list. As we created only one position__c record and same we are passing in URL. So size will be one only
System.assertEquals(1, sic.p.size());

Please try below test class for "saveInputController"
@isTest
public class testsaveInputController{

	public static testmethod void TestMethod1()
	{
		
		Test.startTest();
			
			saveInputController sic=new saveInputController ();
			sic.positionname ='maha'
			PageReference myVfPage =sic.saveposition();
			System.assertNotEquals(null,pageRef);
			
		Test.stopTest();
	}
}

Let us know if this will help you
 
belabela
Hi Amit,
showinputcontrollertest is showing 100% but in logs it is showing following error,if the assertion is failing how it will give 100% pass? and why this error is showing?
02:56:22:065 FATAL_ERROR System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Thanks,
B.Mahanandeesh
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
@isTest
public class showinputcontrollerTest{

	public static testmethod void TestMethod1()
	{
		position__c p= new Position__c(name='maha');
		insert p;
		Test.startTest();

			PageReference pageRef = Page.showinput; // Add your VF page Name here
			//pageRef.getParameters().put('id', String.valueOf(p.Id));
			pageRef.getParameters().put('id', 'maha');
			Test.setCurrentPage(pageRef);
			showinputcontroller sic=new showinputcontroller ();
			System.assertEquals(1, sic.p.size());
		
		Test.stopTest();
	}
}

Please try below test class for "saveInputController"
@isTest
public class testsaveInputController{

	public static testmethod void TestMethod1()
	{
		
		Test.startTest();
			
			saveInputController sic=new saveInputController ();
			sic.positionname ='maha'
			PageReference myVfPage =sic.saveposition();
			System.assertNotEquals(null,pageRef);
			
		Test.stopTest();
	}
}
Please let us know if this will help you

 
This was selected as the best answer
belabela
Hi Amit,
Its working fine, and why it didn't take String.valueOf(p.Id)  as it also should give value (name)of that id ,can you explian it?

Thanks,
B.Mahanandeesh
Amit Chaudhary 8Amit Chaudhary 8
Because in your code you are using name field to fatch record

public with sharing class showinputcontroller {
public List<position__c> p{get;set;}
public showinputcontroller(){
p=[select name from position__c where name like :ApexPages.currentPage().getParameters().get('id') limit 5];
}
}

That is why i added below line in test class.
pageRef.getParameters().put('id', 'maha');

Please let us know if this will help you
 
belabela
Hi Amit,

Means String.valueOf(p.Id)  will only give single value not record is it right?

Thanks
Mahanandeesh.
Amit Chaudhary 8Amit Chaudhary 8
No You are using name field in query that is why you need to add Name not id in test class.

If you want to use Id then please update your code like below:-
public with sharing class showinputcontroller
{
    public List<position__c> p{get;set;}

    public showinputcontroller(){
        p=[select name from position__c where id = :ApexPages.currentPage().getParameters().get('id') limit 5];
    }

}

Test class like below

@isTest
public class showinputcontrollerTest{

    public static testmethod void TestMethod1()
    {
        position__c p= new Position__c(name='maha');
        insert p;
        Test.startTest();

            PageReference pageRef = Page.showinput; // Add your VF page Name here
            pageRef.getParameters().put('id', String.valueOf(p.Id));
            Test.setCurrentPage(pageRef);
            showinputcontroller sic=new showinputcontroller ();
            System.assertEquals(1, sic.p.size());
        
        Test.stopTest();
    }
}
belabela
Hi Amit,

Thank you so much ,I have studied many articles on testclasses but I cant able to understand it,But your answers made me comfort on test classes.You have cleared many doubts on testclasses and other code.I think this page will help people to understand on testclasses.

Thanks and Regards,
B.Mahanandeesh.