I have a previous question:

How to achieve ~100% code coverage with if-then-else statements?

I followed Peter Knolle advice and so far I have 90% coverage. I’m Just going through the code when I have time to reach the max coverage possible, but I ended up having multiple test codes for the same APEX code where each one represents a different scenario. Is it possible to add them up into one code?

For example [referring to the example in the link above] when I try adding up two test codes in one file, and I need to delete an account so I can change things in the account and then insert the new account,

It tells me that I have a duplicate record when I try to run:

System.assertEquals(null, retPageRef, 'PageReference returned should be null');

How can I delete the records completely? Using delete account does not seem to work

  • You can most definitely delete SObjects in a testmethod and they will be deleted. Perhaps your delete DML statement is failing due to some trigger validation preventing the delete or the running user doesn't have privileges to delete the record. Another possibility is that each subsequent test of the controller requires you to reinstantiate it so you don't have any artifacts in the controller's variable stste from the previous test.
    – cropredy
    Jan 14 '14 at 1:44

Depending on how complicated the terms of the if statement are I'd do different things.

If it's a simple switch based on some user input then doing it in one method is perfectly fine, if things are more complicated than that it's often easier to read and understand the test code when you have a method per scenario.

You can often write the tests for an entire controller in a single method, but it can get messy and test code is something you will always be coming back to in order to update and fix it as it depends on so many other factors; therefore it's code that you want to be as easy to maintain as possible, so let that guide your decision.

Your particular issues sound like issues with your test code and you should post that for help with it, but there's no reason why you shouldn't be able to delete the account you've created and inserted. Also, consider whether you need to delete it or if updating the record will be enough.

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.