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

Help with test class please..

Hi all, I'm  newbie in apex and visulaforce development, I have the following apex class:

public with sharing class UserAccountCtrl {
    public Id UserAccountId{get;set;}
    public String ErrorMessage{get;set;}
    public UserAccountCtrl(){  
            Id userId = UserInfo.getUserId();
            User us = [select Id, ContactId from User where Id =: userId];
            if(us.ContactId == null)
                ErrorMessage = 'The user logged is not related to any contact';
            Contact cont = [select Id, AccountId from Contact where Id =: us.ContactId];
            UserAccountId = cont.AccountId; 
        catch(Exception ex)
            ErrorMessage = ex.getMessage();


and visualforce code:

<apex:page controller="UserAccountCtrl" 
<a href="/{!UserAccountId}" target="_parent">Account</a>
How to write a test class for this?? Thanks in advance..





First of all, please go through a few documents explaining the need/way for a test class.

A few links that might help:


For the above class, you can use the below test coverage class:


public class MyTestClass{
	private static void test_UserAccountCtrl(){
		// create data
		// in your class, we are accessing user and contact data 
		// case 1 - for a non-portal user that doesn't have a Contact
		UserAccountCtrl controller = new UserAccountCtrl();
		// add other required fields for Account if any
		Account a = new Account();
		a.Name = 'testAccount';
		insert a;
		// add other required fields for Contact if any
		Contact c = new Contact();
		c.LastName = 'testing';
		c.AccountId = a.Id;
		insert c;
		Id ProfileId = [Select Id From Profile Where Name = 'YOUR PORTAL PROFILE NAME' LIMIT 1].Id;
		// case 2 - for a portal user that has a Contact
		 User u = new User(alias = 'standt', email='',
		emailencodingkey='UTF-8', lastname='lastname', languagelocalekey='en_US',
		localesidkey='en_US', profileid = ProfileId, contactId=c.Id,
		timezonesidkey='America/Los_Angeles', username='');
		insert u;
		// now run the below code as a portal user, here you'll get the contact id for the user
			controller = new UserAccountCtrl();


 Let me know if any questions/issues. Thanks!