2

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?

4
  • 2
    You can generate a string using a loop, stringbuilder, or array. Commented Feb 25, 2019 at 15:45
  • Consider using a stream and a stream reader, instead of having the whole string in memory. Commented Feb 25, 2019 at 15:48
  • do you need to test for < 0? Commented Feb 25, 2019 at 16:55
  • @RufusL I am not sure, it isn't my code originally. I don't see how it could return a negative value here. Commented Feb 25, 2019 at 17:11

3 Answers 3

7

string has a constructor that lest you specify a length and a characer to repeat:

string longString = new string('a',0x0FFFFFFF + 1);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.