How to add static imports to IntelliJ IDEA live template - java

I need to port the following Eclipse template to IntelliJ IDEA
/**
* See method name.
*/
#${testType:newType(org.junit.Test)}
public void should${testdesc}() {
// given ${cursor}
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
What I've got so far is
/**
* See method name.
*/
#org.junit.Test
public void should$EXPR$() {
// given $END$
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
And then tick the Shorten FQ names flag.
What's the IDEA equivalent for the ${staticImport:importStatic()} expression?

You cannot just import the static imports in a live template. (You can for a file template, see below). But you can when using a method in the template. You just simply fully qualify the class and then select both the "Shorten FQ names" and "Use static import if possible" options. For example, the following:
org.junit.Assert.assertEquals("$END$", $EXPECTED$, $ACTUAL$);
Will result in:
import static org.junit.Assert.*;
. . .
assertEquals("my error message", myExpectedVar, myActualVar);
when invoked. (I have the $EXPECTED$ and $ACTUAL$ variables set to variableOfType("") with corresponding default values expected and actual)
If you want certain static imports to be included in all your unit tests, then I would recommend editing the "Class" File and Code Template. For example:
package ${PACKAGE_NAME};
#if ($NAME.endsWith("Test"))
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.*;
#end
#parse("File Header.java")
public class ${NAME}
{
#if ($NAME.endsWith("Test"))
// Add any default test methods or such you want here.
#end
}
Keep in mind however, the static import will immediately be removed if you have the "Optimize imports on the fly" option (in IDE Settings > Editor > Auto import) turned on, unless you also include a method (or other code) that makes use of the static import.

Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}

Related

Eclipse formatter automatically inserts two blank lines after package declaration

Am using Eclipse Neon 3 and was making my usual edits to the formatter when I noticed that everytime I create a new class, it creates two new (or blank) lines between the package declaration and the actual class itself!
package com.myapp;
public class MyClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
How to setup the Eclipse formatter to only include one blank line (initially), especially if there's no import declarations used yet, like this:
package com.myapp;
public class MyClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Been trying to fix this myself and would appreciate if someone could point me in the right direction.
Review the code template that was set up in Eclipse by opening up Window > Preferences > Java > Code Style > Code Templates and configure the generated code for New Java Files under the Code header.
The default template given provided was
${filecomment}
${package_declaration}
${typecomment}
${type_declaration}
and the generated code as follows
package com.personal.test.com.personal.test;
public class AppTest {
}
If the template was modified to this, note the extra blank lines.
${filecomment}
${package_declaration}
${typecomment}
${type_declaration}
The following is generated
package com.personal.test.com.personal.test;
public class AppTestWithSpaces {
}

How to use java properties file in OSGI Declarative Services Annotations

I'm trying to use bndtools to create my OSGI program. Here is my previous code, and it can work well with the felix console.
package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;
#Component(
service=PublishCommand.class,
property={
CommandProcessor.COMMAND_SCOPE + ":String=example",
CommandProcessor.COMMAND_FUNCTION + ":String=publish",
}
)
public class PublishCommand {
private Publisher publishSvc;
#Reference
public void setPublisher(Publisher publishSvc) {
this.publishSvc = publishSvc;
}
public void publish(String content) {
publishSvc.start();
long result = publishSvc.publish(content);
System.out.println(result);
publishSvc.stop();
}
}
Now, I want to change the annotation like this:
package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;
#Component(
service=PublishCommand.class,
properties="com/buaa/ate/service/data/command/config.properties"
)
public class PublishCommand {
private Publisher publishSvc;
#Reference
public void setPublisher(Publisher publishSvc) {
this.publishSvc = publishSvc;
}
public void publish(String content) {
publishSvc.start();
long result = publishSvc.publish(content);
System.out.println(result);
publishSvc.stop();
}
}
And this is my properties file:
config.properties
It's content like this:
osgi.command.scope\:String:example
osgi.command.function\:String:publish
When I run the program, input the command 'publish something', and then the problem happens:
'gogo: CommandNotFoundException: Command not found: publish'
So, what should I do to fix the problem?
Well, I just realize that it's so easy to fix the problem. This is a part of the osgi javadoc:
property
public abstract java.lang.String[] property
Properties for this Component.
Each property string is specified as "key=value". The type of the property value can be specified in the key as key:type=value. The type must be one of the property types supported by the type attribute of the property element of a Component Description.
To specify a property with multiple values, use multiple key, value pairs. For example, "foo=bar", "foo=baz".
See Also:
"The property element of a Component Description."
Default:{}
So I add the 'type' property to config.properties, and then the code can work well. Here is the current properties file:
current properties file
And it's content like this:
osgi.command.scope=example
osgi.command.scope\:type:String
osgi.command.function=publish
osgi.command.function\:type:String
The program can work well now.

How to check Toolbar title in android instrumental test?

I found great instrumental test tutorial on YT Advanced Android Espresso. I took code from there with small adjustment to my needs.
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withChild;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
...
#Test
public void checkToolbarTitle() {
String toolbarTitile = getInstrumentation().getTargetContext().getString(R.string.my_bus_stops);
onView(allOf(isAssignableFrom(TextView.class), withParent(isAssignableFrom(Toolbar.class)))).check(matches(withText(toolbarTitile)));
}
Unfortunatelly it does not work for me. Test failed with:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (is assignable from class: class android.widget.TextView and has parent matching: is assignable from class: class android.widget.Toolbar)
What is wrong with it? How can I test it in other way?
This works for me:
onView(allOf(instanceOf(TextView.class), withParent(withId(R.id.toolbar))))
.check(matches(withText("toolbarTitile")));
SOLUTION
The method is fine. As Chiu-Ki Chan wrote in her tutorial you can "pinpoint that one particular view".
BUT you have to make sure you imported proper Toolbar:
import android.support.v7.widget.Toolbar;
instead of:
import android.widget.Toolbar;
Here's an alternative (and more idiomatic approach):
onView(withId(R.id.toolbar)).check(matches(hasDescendant(withText(toolbarTitle))))
If you're using an ActionBar, not a Toolbar, use this:
onView(allOf(instanceOf(TextView.class),
withParent(withResourceName("action_bar"))))
.check(matches(withText("My ActionBar title")));
Note: To quickly add the imports for these methods, put the blinking cursor on the unresolved method, then do Android Studio ➔ Help ➔ Find Action ➔ search for "show context action" or "show intention action" ➔ click on the result option ➔ A popup window will appear ➔ click on "Import static method ...". You can also assign a keyboard shortcut to "Show Context Actions". More info here. Another way is to enable "Add unambiguous imports on the fly" in the Settings.
I don't remember if I wrote this myself, or if I found it somewhere, but this is how I check toolbar titles:
public static Matcher<View> withToolbarTitle(CharSequence title) {
return withToolbarTitle(is(title));
}
public static Matcher<View> withToolbarTitle(final Matcher<CharSequence> textMatcher) {
return new BoundedMatcher<View, Toolbar>(Toolbar.class) {
#Override
public boolean matchesSafely(Toolbar toolbar) {
return textMatcher.matches(toolbar.getTitle());
}
#Override
public void describeTo(Description description) {
description.appendText("with toolbar title: ");
textMatcher.describeTo(description);
}
};
}
This works with all cases. Example assertion: onView(withId(R.id.toolbar)).check(matches(withToolbarTitle("title")));

Junit + Netbeans: Doesn't find methods inside class for test

I have made a very simple class to test for proper Junit test generating. The problem is that when I create a Junit test, it doesn't find my methods for some reason. I have tried with multiple very simple classes without success. I am starting to think I set up Junit for the project incorrectly. Here is my simple class I am trying to test:
package controller;
public class SampleProgram {
public int multiply(int x1, int x2){
return x1 * x2;
}
}
Here is what is generated when I create a Junit Test in Netbeans:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ProgramTest {
public ProgramTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
}
Any help as to why my method isn't being found and generating the test is much appreciated. I have not used Junit before and am completely lost. Thanks
EDIT
Here is a screenshot of my editor with a Junit test provided from Jose Martinez.
The imports are the defaults for when netbeans creates a Junit test.
Screenshot
If you are referring to Netbeans auto unit test creator functionality then... When you right click a class in Nebeans project tab and select Tools -> Create/Update Tests, a dialog box will pop up. In the Code Generation box, under Method Access Levels, select the Public radio button.
But usually this auto feature is just to get you started. You will have to get comfortable with creating your own tests. In this case a good unit test for multiply might look something like this.
#Test
public void testMultiply() {
System.out.println("testingMultiply");
SimpleProgram instance = new SimpleProgram();
int expected = 12;
int p1 = 3;
int p2 = 4;
int actual = instance.multiply(p1, p2);
assertEqual(expected, actual);
}
You should select the correct Code Generation items from the wizard.

How to print imported java libraries?

Is there a way to print within a Java Code the libraries that has been imported, and available during the execution?
For example :
import javax.swing.JFrame;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//some code
}
}
I need to print javax.swing.JFrame.
If you need the actual imports used in your source code (rather than using the information in the bytecode), you can use a library called QDox which will parse your source code and can get a list of the imports you use:
Main.java
import com.thoughtworks.qdox.JavaDocBuilder;
import javax.swing.JFrame;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JavaDocBuilder java = new JavaDocBuilder();
java.addSourceTree(new java.io.File("."));
for (String i : java.getClassByName("Main").getSource().getImports()) {
System.out.println(i);
}
}
}
Compile and run with:
# If you don't have wget, just download the QDox jar by hand
wget -U "" http://repo1.maven.org/maven2/com/thoughtworks/qdox/qdox/1.12/qdox-1.12.jar
javac -classpath qdox-1.12.jar Main.java
java -classpath qdox-1.12.jar:. Main
The output is:
com.thoughtworks.qdox.JavaDocBuilder
javax.swing.JFrame
I don't think that there is a way to do that. Imports are only a syntactic aid for the programmer and are not reflected in the compiled class files. Anyway, what do you need such a feature for?

Categories