Search code examples
vimvim-macros

vim to generate code template dynamically


I have to write test cases which contains repetive code.

  1. The name of the method should be the ClassName delimitted with _ ex: class_name_test
  2. The object name should be classNameObj and the mock method should take ClassName.class
  3. The genericObj.call statement is common for all methods The sayHello should be bound to classNameObj and the remaining result is common
  4. The commonMethods is common for all objects

Instead of copy pasting and changing the ClassName and classNameObj, I am interested in automating this using Vim. Is is possible to do this to which if I pass the Class name, the rest should be generated?

The method template is mentioned below.

@Test
public void stop_video_request_valid_data() throws Throwable {
    ClassName classNameObj = mock(ClassName.class);
    when(genericObj.call()).thenReturn(new Object[]{classNameObj});
    when(classNameObj.sayHello()).thenReturn("Hello");
    commonMethods();
}

Solution

  • snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.

    There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.