Reputation: 320
I'm currently using C#, but I believe the question applies to more languages.
I have a method, which takes a string value, and throws an exception, if it's too big. I want to unit test it that the exception is correct.
int vlen = Encoding.UTF8.GetByteCount(value);
if (vlen < 0 || 0x0FFFFFFF < vlen)
throw new ArgumentException("Valid UTF8 encodded value length is up to 256MB!", "value");
What is the best way to generate such a string? Should I just have a file of that size? Should I create such a file every time running unit tests?
Upvotes: 2
Views: 3514
Reputation: 152566
string
has a constructor that lest you specify a length and a characer to repeat:
string longString = new string('a',0x0FFFFFFF + 1);
Upvotes: 6
Reputation: 43896
You can simply use a StringBuilder
:
StringBuilder builder = new StringBuilder();
builder.Append('a', 0x10000000);
string s = builder.ToString();
//Console.WriteLine(s.Length);
YourMethodToTest(s);
This takes no measurable time at my machine and I'm sure there won't be a serious performance issue on your machine either.
Upvotes: 1
Reputation: 8183
What I would usually use in Unit Tests is a package called AutoFixture
.
With that you can do the following to generate a large string:
string.Join(string.Empty, Fixture.CreateMany<char>(length))
Upvotes: 0