Fast file or standard input processing
import java.io.*; import java.util.StringTokenizer; public class App { private static String TEST_FILE = "file.txt"; private PrintWriter pw; private BufferedReader br; App(boolean skip) throws FileNotFoundException { this.pw = new PrintWriter(System.out); File file = new File(TEST_FILE); if (!skip && file.exists()) { br = new BufferedReader(new java.io.FileReader(TEST_FILE)); } else { br = new BufferedReader(new InputStreamReader(System.in), 1 << 16); } } void doit() throws IllegalArgumentException, IOException { StringTokenizer s = new StringTokenizer(br.readLine()); // do sth w/ s String result = "sth"; pw.println(result); pw.flush(); } public static void main(String[] args) throws IllegalArgumentException, IOException { new App(false).doit(); } }
How to create InputStream from String?
public InputStream stringInputStream(String payload) { return new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8)); }
How to create Mockito mock as Spring bean?
<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="com.package.Dao" /> </bean>
Why Mockito @Captor is so good?
We want to create Captor for List
ArgumentCaptor<List> filterCaptor = ArgumentCaptor.forClass(List.class); verify(listener).doSomething(eq("foo"), filterCaptor.capture());
The code compiles and works, but there is a warning about the unchecked assignment. @Captor annotation solves the problem:
@Captor private ArgumentCaptor<List<EntityCriterion>> filterCaptor;
Spring context integration in Unit Tests
This snippet shows how integration test involving Spring contexts should be written. If you have numerous unit tests similar to the one below, the Spring context (given as the parameter of @ContextConfiguration annotation) will be read only once and re-used. This really improves the speed of running mvn test command.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-test-context.xml") public class FooImplTest { @Autowired private FooImpl fooImpl; @Test public void someWeirdTest {} }
As you can notice @Autowired annotation is used for automatic loading of a bean. The context in this example should contain a bean of type FooImpl (in this case the wiring is made according to the bean type).
How to add TestNG to your project?
Add proper dependency to your pom.xml:
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.1.1</version> <scope>test</scope> </dependency> </dependencies>
And Java code with Unit Test:
import org.testng.annotations.*; public class SomeUnitTest { @Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000) public void basicTest() throws Exception { // given // when // then assertEquals(expected, result); } }
Another useful set of methods to replace boilerplates
org.springframework.web.util.WebUtils
class contains for example:
public static Cookie getCookie(HttpServletRequest request, String name) { Assert.notNull(request, "Request must not be null"); Cookie cookies[] = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie; } } } return null; }
JavaScript: how to log JSON using console.log?
this.eventJson = { resource: { summary: this.configuration.eventName, description: this.configuration.eventDescription, } }; console.log("and the JSON looks like this " + JSON.stringify(this.eventJson));
MongoDB: Convert collection to JS map
“Old-school” JS:
var usersDict = {}; db.getCollection("users").find().forEach(user => { usersDict[user._id] = user; });
Wtih reduce():
var usersDict = db.getCollection("users").find().toArray().reduce(function(map, obj) { map[obj._id] = obj; return map; }, {});