How to Initialize Lists for Unit Tests
I like clean simple condensed code, esecially when it comes to tests. I really do not like seeding the lists this way
List<String> values = new ArrayList<String>();
values.add("test");
values.add("foo");
values.add("bar");
bean.setValues(values);
This method requires a lot of keyboard interaction if you do not use your mouse. Having to navigate lines of code with a keyboard can interrupt ones flow. Or you can use the mouse to highlight, copy and paste but who likes touching their mouse when coding.
So i started intializing my list like this for quite some time.
List<String> values = new ArrayList<String>(){{
add("test");
add("foo");
add("bar");
}};
bean.setValues(values);
If you are not familier with double brace initializers then this code can be difficult to read and even can seem invalid to some. But this solved the problem by reducing my keyboard interaction so I used it.
Just recently I started using this method.
String[] values = {"test", "foo", "bar"};
bean.setValues(Arrays.asList(values));
This really solved my problem with reducing my keyboard interaction even more than before and it also made the code easy to read and condensed.