How to write test cases in a Salesforce application to check its code coverage?

476    Asked by dipesh_9001 in Salesforce , Asked on May 3, 2023

I want to upload my application on appExchange. Now I want to know about all the steps to do my task. Here I noticed that we have to write test cases for the code to check its coverage. And at least 70% code coverage is necessary to upload an app on appExchange. How can we make test cases and in which area of code we have to make test cases, and what is the process of getting code coverage up to 70% of the whole code. Also differentiate between test class and triggers. Thanks. Any help will be appreciated.

Test cases in salesforce are nothing more than Apex classes. Take a look at this documentation for an introduction. Think of Test Classes as a programmatic way of testing use cases.

For instance, if you have a button that calls a certain function, you'd want to call that in your code and then check whether or not the outcome is as expected.

As a mundane example, if you have a piece of code like the following:

public Integer add(Integer x, Integer y) { return x + y; }
You'd want to call that function and assert that the two parameters you pass in return the expected output. If x = 2 and y = 3, you know the answer is 5, you'd want to assert that you actually get 5. If you don't, you have a problem.
and on which area of code we have to make test cases

All of it. Salesforce's minimum requirement is 75%, but they advise 100% and rightly so. The reason for this is that you want to ensure that every line of code, under different use cases, works as expected. Sometimes, this isn't always possible. But aim for it as best as you possibly can.

      what is the process of getting code coverage up to 70% of the whole code

Literally what I mentioned above!

Also differentiate between test class and triggers

I think you might be a little confused here as Triggers and Test Classes aren't really equivalent unless I'm misinterpreting what you're asking. Test classes are designed for what I've explained above, Triggers fire on DML. Triggers should also be covered by a test class which can usually be pretty easily achieved by simulating data being inserted/updated/deleted/undeleted from the database.

It's what happens when that trigger is fired, and again, checking that when it is fired, the system and your code does what you expect.

I appreciate this is quite a simplistic answer, but it's a really, really broad question. There's tons of material on unit testing and although it takes a little bit of time getting your head around it, it's incredibly important! Imagine pushing out an update to your app, forgetting that something you changed has a knock on effect to something you hadn't considered and then mistakenly breaking the entire thing. Test classes are there to help prevent that.


Your Answer

Interviews

Parent Categories