Mocking a method from Context.java Object

Good afternoon folks!

I am currently working on my first pull request which involves adding more unit tests for a particular method. I am still new to the conventions so before I proceed, I would like to gain input from this community.

So the method I am working on is:

	public Patient getPatientOrPromotePerson(IPreformatted textnteger patientOrPersonId) {
		Patient patient = null;
		try {
			patient = Context.getPatientService().getPatient(patientOrPersonId);
		}
		catch (ClassCastException ex) {
			// If the id refers to Person not Patient, it sometimes will cause class cast exception
			// We will attempt to retrieve the Person and promote to Patient
		}
		if (patient == null) {
			Person toPromote = Context.getPersonService().getPerson(patientOrPersonId);
			if (toPromote != null) {
				patient = new Patient(toPromote);
			}
		}
		return patient;
	}

I currently want to mock Context.getPatientService(), however it is a static method:

public static PersonService getPersonService() {
	return getServiceContext().getPersonService();
}

Does anybody have a solution to this? Thank you! Also if there is a format as to how you would prefer me to paste the code into this paste, please let me know so I can help make it easier to read.

Hello @vincentvtran ,welcome to the openmrs community ,

Use https://pastebin.com/ to paste your code and error logs

Use power mockito to deal with static methods

1 Like

Thanks its as simple as

public static PersonService getPersonService() {
	return context.getPersonService("your custom service class or object you had created");

} Note for you to be to mock a method from context, you will have to first configure your service classes in moduleApplicationContext.xml, This link here can be of help.

1 Like