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
up_skyup_sky 

How to wirte the test class for this

I am writing some unit tests for one of my apex classmethods that is defined as follows:

 

I got error System.NullPointerException: Attempt to de-refference a null object. My Code Coverage is 30%

 

public with sharing class CMIARequest {
	private Map<String, String> cmds;
		
	private CMIARequest(MAP<String, String> cmds) {
		this.cmds = cmds;		
	}
	
	public static CMIARequest construct(MAP<String, String> cmds) {
		string cmd = ApexPages.currentPage().getParameters().get('command');
		if (cmd == null)
			throw new CMIAException('No command specific');
		return new CMIARequest(cmds);
	}
	
	public boolean validate() {		 
		String sid = cmds.get('sid');
		if (sid == null)
			throw new CMIAException('no session ID specific');
		return CMIASessionManager.validateSession(sid);
	}
	
	public String getSessionID() {
		return cmds.get('sid');
	}
	
	public String getCommand() {
		return cmds.get('command');
	}	
	
	public String getParam(String key) {
		return cmds.get(key);
	}
	
	public String getRequestString() {
		Set<String> keys = cmds.keySet();
		CMIAJsonEntryMap m = new CMIAJsonEntryMap();
		for (String k : keys) {
			m.addEntry(k, cmds.get(k));
		}
		return m.render();
	}
	
	static testmethod void unitTest() {
		
		String key = 'MyKey';
		String command = 'getSfUserInfo';
		Map<String, String> cmds;
		
		string cmd = ApexPages.currentPage().getParameters().put('command',command);
		CMIARequest.construct(cmds);
	
        CMIARequest cmr = new CMIARequest(cmds);
        Boolean validate = cmr.validate();
        cmr.getSessionID();
        cmr.getCommand();
        cmr.getParam(key);
        cmr.getRequestString();
        
		}
}

 

bob_buzzardbob_buzzard

Your cmds map is null, so when you call the validate method, this line fails:

 

String sid = cmds.get('sid');

 

as it is trying to call the get method of a null list.

 

If you instantiate an empty list that should fix it:

 

static testmethod void unitTest() {
		
String key = 'MyKey';
String command = 'getSfUserInfo';
Map<String, String> cmds=new Map<String, String>();
		
...