I have a function createWithRecordTypeIfExists(String recordType). Its logic goes like this:

Check whether a record type for this object exists in the org.

  • If yes, create a new record with this record type.
  • If no, create a new record with recordTypeId null.

My question is: how do I unit test this logic? Shall I do assert like below?

But it doesn't feel like a unit test anymore, too heavy and conditional embedded.

  //assert validate recordTypeId fetched from the org;
  //assert validate recordTypeId == null;

1 Answer 1


It depends mainly on whether this function returns something. If so, you can write two test methods and check at the end which RT id returns, the existing one or the new one.

  • but the logic is still determined by whether such record type exists in the org or not. Since it is not part of my solution, there is no guarantee without referring to the record types in the org.
    – Xi Xiao
    Apr 10, 2019 at 13:59
  • @XiXiao tests are usually based on assumptions. One can assume that some RT will certainly be on every environment?
    – Adamo
    Apr 11, 2019 at 6:58
  • the challenge is the solution was developed with unlocked package in scratch org, which doesn't have this record type, while in production or sandbox, it exists. In order to green light the test in both scenarios I need to use if assert else assert to check the record type existence , which feels wrong.
    – Xi Xiao
    Apr 11, 2019 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.