Need an example for using Junit in Intellij Idea - junit

Maybe it's just me, but I cannot understand the documentation regarding Junit test integration in Intellij Idea. What I am looking for is a simple tutorial example, such as:
Here is a method calculating 2+2, and here is a test class testing it to be 4. This is the checkbox you set to make it go. If there is already such a thing on the web or inside the Intellij Idea help, please refer me to it.
I use Idea 7.0.4 and would like to use JUnit 3.8 or 4.*. TIA.

Here is a small sample of how I use intellij with junit
public class MathTest { // Press Ctrl-Shift-F10 here to run all tests in class
#Test
public void twoPlusTwo() { // Press Ctrl-Shift-F10 here to run only twoPlusTwo test
assertThat( 2+2, is( 4 ) );
}
#Test
public void twoPlusThree() { // Press Ctrl-Shift-F10 here to run only twoPlusThree test
assertThat( 2+3, is( 5 ) );
}
}
Once you run the test once, it will show up at the top of the screen as a run "configuration". Then you can either hit the green triangle to rerun the test, or use the debug triangle to run in debug mode with breakpoints enabled.

Related

Difference in running Cucumber-JVM vs Cucumber runner(Junit)

I am fairly new to Cucumber. I was experimenting with it by just creating few test features when I noticed the difference when running a single feature vs running the whole suite (from the IntelliJ).
I noticed that when I run single feature it runs using the cucumber-jvm option and in this case, the CucumberConfig(the blank class to define the runner and cucumber options) and the Runner is not utilized. However, when I run the whole suite it runs as a JUnit test and obviously, in this case, the Config class and the runner comes into the picture.
I confirmed this with the following sample code:
#RunWith(CustomRunner.class)
#CucumberOptions()
public class CucumberConfig {
#BeforeClass
public static void beforeClass()
{
System.out.println("This is run before Once: ");
}
#AfterClass
public static void afterClass()
{
System.out.println("This is run after Once: ");
}
}
CustomRunner
public class CustomRunner extends Cucumber {
public CustomRunner(Class clazz) throws InitializationError, IOException {
super(clazz);
System.out.println("I am in the custom runner.");
}
}
Also, I understand that while running as cucumber-junit we can't pass specific feature to run as in cucumber-jvm. Correct me if I am wrong.
My doubt is, is this the default behavior or am I doing something wrong. And, if this is default how can I make cucumber to always use the Config file.
I'll appreciate if someone can provide some insight on this.
When you're using IntelliJ IDEA to run the tests, IDEA will use cucumber.api.Main to run the tests. As such it will ignore CucumberConfig neither will it run #BeforeClass nor #AfterClass, these are only used by the JUnit runner.

Launching JUnit jupiter tests from inside a main method?

I have a Java class with a main method that I invoke to occasionally run some tests. Specifically, I'm trying to come up with a solution for quickly testing various code snippets that use the AWS SDK to create/read some S3 objects. I'm not really trying to build regular unit/integration tests, and I'm not interested in mocking the S3 code. I'm trying to quickly develop/debug some code using a test framework. I found the following SO question, and the answer about using JUnit5 Jupiter's Launcher and it intrigued me:
How do I run JUnit tests from inside my java application?
So I read the Junit5 chapter on the Launcher API and followed the example code. I came up with something like this:
class S3ManualTest {
public static void main(String[] args) {
LauncherDiscoveryRequest request =
LauncherDiscoveryRequestBuilder
.request()
.selectors(selectPackage("com.xyz.s3util"),
selectClass(S3ManualTest.class),
selectMethod(S3ManualTest.class, "happyPath")
)
.build();
Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.execute(request, listener);
TestExecutionSummary summary = listener.getSummary();
System.out.println("# of containers found: " + summary.getContainersFoundCount());
System.out.println("# of containers skipped: " + summary.getContainersSkippedCount());
System.out.println("# of tests found: " + summary.getTestsFoundCount());
System.out.println("# of tests skipped: " + summary.getTestsSkippedCount());
}
void happyPath() {
assertTrue(true); // Do useful stuff here
}
}
The launcher doesn't find any tests to run, even though I specifically selected the "happyPath" method. I have tried annotating the happyPath() method with #Test, and that seems to work, but it also has the undesired side effect that the method gets executed if I run all tests in that package, either from gradle, or from inside the IDE. Essentially, I want my test methods to be invoked with the JUnit5 framework, but only when I manually run the main method in the class. I was thinking about some custom annotations, or implementing some interface that would get picked up by the test engine, but haven't gone down that route yet. I'm guessing there's some easy way of accomplishing what I'm trying to do. Thanks.
I could only find a work around: disabling the happyPath() test method by default and override it in your program like explained here: https://junit.org/junit5/docs/current/user-guide/#extensions-conditions-deactivation
#Test
#Disabled
void happyPath() {
assertTrue(true); // Do useful stuff here
}
And in your launcher setup, deactivate the DisabledCondition:
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
.request()
.selectors(selectMethod(S3ManualTest.class, "happyPath"))
.configurationParameter(
"junit.jupiter.conditions.deactivate",
"org.junit.*DisabledCondition")
.build();
You may also specify a dedicated switch, if you don't want deactivate DisabledCondition for the entire run:
#Test
#EnabledIf("'true'.equals(junitConfigurationParameter.get('manual'))")
void happyPath() {
assertTrue(true); // Do useful stuff here
}
with
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
...
.configurationParameter("manual", "true")
.build();
The second work-around, if applied to more then a few methods, screams for a dedicated ExecutionCondition extension. See details at https://junit.org/junit5/docs/current/user-guide/#writing-tests-conditional-execution-scripts

How to get Play Framework current running application instance in JUnit test cases

I am working in Java Play Framework project. I want to write some JUnit test cases to test my application code.
Now for my JUnit cases, I need to initiate the play server Application to get all the configuration.
How do I get current play Application instance to initiate my Global ServerConfig in JUnits
Example type of code:
#Test
TestCode(){
Global.init(CurrentApplication_Instance);
//tes
}
Where CurrentApplication_Instance should be current running play.Play.application().
You can extend your Test-Class from play.test.WithApplication which starts an application at the beginning of the test and provides it as a property. So you could:
public class MyTest extends play.test.WithApplication {
#Test
TestCode(){
Global.init(app);
}
}

How to jmock Final class

I was trying to mock final class(AnyFinalClass.java) in junit using JDave in eclipse.
public void setUp() throws Exception {
Mockery mockery = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
AnyFinalClass any = mockery.mock(AnyFinalClass.class);
}
I am trying to use jdave-unfinalizer-1.1.jar as javaagent but didnt had any success. I tried multiple things but getting following exception
java.lang.IllegalArgumentException: Cannot subclass final class class AnyFinalClass
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
Can someone who has already tried jdave unfinalizer give me exact step how to make it work on eclipse.
I set following in eclipse.ini file but got the problem
-Xbootclasspath/a:lC:\WS\JunitTesting\jars\asm-3.0.jar
-javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
While running executing the junit, I gave vm argument as
javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
I am not sure what will be the code. jdave is not having the code and its site is pointing to some other site which is not working. Please correct my code or provide your same working code.
Any help is highly appreciated.
from Enhancer.java line 446:
if (TypeUtils.isFinal(sc.getModifiers()))
throw new IllegalArgumentException("Cannot subclass final class " + sc);
I have not worked with JDave but with another mocking frameworks and the only one that allows to mock a final class was powermock
Look also here
In order to get unfinalizer running you have to put -javaagent:path_to_unfinalizer/jdave-unfinalizer-1.1.jar in the VM arguments of the run configuration of the test.
I also had to include several dependencies of jdave-unfinalizer in the classpath of the project from which the tests ar being launched. These are, taken from the maven definitions of jdave:
jdave-core 1.1
cglib-nodep 2.1_3
objenesis 1.0
asm 3.0
asm-commons 3.0
asm-tree 3.0

Globally setting a JUnit runner instead of #RunWith

Without looking into JUnit source itself (my next step) is there an easy way to set the default Runner to be used with every test without having to set #RunWith on every test? We've got a huge pile of unit tests, and I want to be able to add some support across the board without having to change every file.
Ideally I'm hope for something like: -Djunit.runner="com.example.foo".
I don't think this is possible to define globally, but if writing you own main function is an option, you can do something similar through code. You can create a custom RunnerBuilder and pass it to a Suite together with your test classes.
Class<?>[] testClasses = { TestFoo.class, TestBar.class, ... };
RunnerBuilder runnerBuilder = new RunnerBuilder() {
#Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
return new MyCustomRunner(testClass);
}
};
new JUnitCore().run(new Suite(runnerBuilder, testClasses));
This won't integrate with UI test runners like the one in Eclipse, but for some automated testing scenarios it could be an option.
JUnit doesn’t supporting setting the runner globally. You can hide away the #RunWith in a base class, but this probably won't help in your situation.
Depending on what you want to achieve, you might be able to influence the test behavior globally by using a custom RunListener. Here is how to configure it with the Maven Surefire plugin: http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html#Using_custom_listeners_and_reporters