4

I am writing a test class for a file uploader thingamajig I wrote. The class takes a blob representing the contents of the file. So far everything is going well and I've got 93% code coverage.

However, I'm a perfectionist and I want to bring that figure up to 100%. There's a part of my code that handles an exception that gets thrown when the file is too large to be inserted in the Documents object (a file over 5mb). I want to know if there's a way I can generate a blob over 5 MB in my test class to trigger that exception handler.

How do I generate a blob over 5MB programmatically in an Apex class? I tried making a massive string the way I would in python (i.e. String reallyBigString = "foo" * some_huge_number_here;) but that doesn't work since Apex doesn't allow arithmetic operations on a string. Any way I can do this?

0

1 Answer 1

10

You can use the string repeat method to build a long string, and then pass that to a Blob.

Blob data = Blob.valueOf('a'.repeat(5242880));
4
  • Thank you, you're a genius. I just changed it to 5542880 since 5242880 wasn't big enough. Got that 100% coverage now. You're awesome
    – ag415
    Commented Oct 9, 2017 at 20:35
  • 1
    Glad I could help. :)
    – Adrian Larson
    Commented Oct 9, 2017 at 20:36
  • For those who find this answer in the future -- note you will get "System.LimitException: String is too long" if you try to generate a string that is much longer than this. Anything above 6,000,000 characters throws this exception. Commented Dec 8, 2020 at 16:48
  • Good to know, thanks!
    – Adrian Larson
    Commented Dec 8, 2020 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .