0

I have a method that returns:

Map<String, List<Account>> results

I want to have a test class that asserts that the map contains two list records with one string value. I can't figure out how to do the assertion. I know that with a debug that there are two records in the list.

I tried this:

List<Account> outerList = results.values();
System.assertEquals(2, outerList.size());

and I get the error:

Illegal assignment from List<List<Account>> to List<Account>

I tried this:

System.assertEquals(2, results.values().size());

and I get the result:

Assertion Failed: Expected: 2, Actual: 1

I tried this:

 System.assertEquals(2, results.size());

and I get the result:

Assertion Failed: Expected: 2, Actual: 1

What am I doing wrong?

1 Answer 1

1

There's only one key, with two elements, so you'd do:

List<List<Account>> accounts = results.values();
System.assertEquals(1, accounts.size(), 'Map should have one key entry');
System.assertEquals(2, accounts[0].size(), 'List should have two accounts in first key');
4
  • You should assert both collections are not null.
    – Adrian Larson
    Commented Feb 22, 2018 at 20:23
  • @AdrianLarson The first collection can't be null; values() never returns a null value, but it would an empty list. The first assertion takes care of that for me. The second list could be null, but then my test would fail with NullPointerException, so I would know that the list wasn't created properly. The second assertion (accounts[0] != null) wouldn't be incorrect, but it's also not necessary.
    – sfdcfox
    Commented Feb 22, 2018 at 20:29
  • You don't know that results is not null. Your tests shouldn't really fail with an NPE...
    – Adrian Larson
    Commented Feb 22, 2018 at 20:35
  • @AdrianLarson I respectfully disagree with the premise that a failed unit test should not be because of an uncaught exception of any kind. The fact that the test failed is sufficient to know something is wrong without explicitly checking null values. (a) I don't write code I don't need to, and the NPE does my work for me, so why not use it. (b) When there is NOT an NPE, my unit tests run oh-so-slightly-faster. While it's a small thing, hundreds or thousands of worthless NPE checks can bog down a successful deployment time.
    – sfdcfox
    Commented Feb 22, 2018 at 21:01

You must log in to answer this question.

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