I know a way to print the classpath of a project at runtime like here:
http://www.mkyong.com/java/how-to-print-out-the-current-project-classpath/
But sometimes the main is even too late, for example when using spring.
Is there a way to print something(e.g. classpath) even before Spring starts the injection process?
Providing some context, i am running a unit test in spring as follows:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:/jmsAppContext.xml")
public class TestProjectProvisioningIntegration
{
....
}
It finds correctly the jmsAppContext.xml, but fails to find one of the properties files.
To get the same effect as you have in the link you posted, you could get the classpath in a static initializer (just do the same as the example, only then in a static { ... } block instead of a main method. The JVM will execute the static initializer first, before loading any other classes your class depends on (other than the classes you reference in the static initializer).
Related
I have an application I want to test:
import foo.ExtClass;
public class App {
public static void main(String[] args) {
ExtClass ext = new ExtClass();
...
}
}
I want to write a unit test for this application, however I do not want to use the foo.ExtClass, but use another mock implementation for the class.
Normally I would use a factory to instantiate the class according to some configuration that can be controlled in the unit test.
However, in this case, I cannot modify the tested app.
I was thinking in the direction of writing a custom class loader to load the mock class instead of the real class - not sure if this is possible without any modification to the tested app, and how.
As an option you can use custom classloader, which will substite your class with a testing one. So basically instead of loading ExtClass from your app package, your classloader will load the same class from your testing package with the mock implementation.
Here is an example:
How to replace classes in a running application in java ?
Also there is very usefull tutorial: https://zeroturnaround.com/rebellabs/reloading-objects-classes-classloaders/
The approach I finally used:
Created a separate project with my mock implementation of foo.ExtClass,
and the unit tests.
This way the mock implementation appeared in the classpath before the real implementation, and the original (tested) project remained untouched.
I am running into trouble with JUnit 5 (5.0 or 5.1) and custom extension.
We are using service loader to load all implementations which then modify how our extension is bootstrapped. These implementations can be loaded just once, so I was thinking of using ExtensionContext.Store and placing it there. Every subsequent test instance would then just load it from Store instead of via service loader.
Now, I am even aware of the hierarchical context structure and I know that there is some "root" context which you can get through ExtensionContext.getRoot(). But this "root" context (instance of JupiterEngineExtensionContext) isn't really root - there is different one for every test instance.
Say you have FooTest and BarTest, then printing out getRoot() for each of them yields:
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext#1f9e9475
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext#6c3708b3
And hence trying to retrieve previously stored information from Store fails.
Is having this limitation intended? It makes the borderline between ClassExtensionContext and JupiterEngineExtensionContext pretty blurred.
Is there another way to globally store some information via extension?
Here is a (very) simplified version of how I tried working with the store (cutting out all other information basically). I also added some System.out.print() calls to underline what I am seeing. Executing this extension on two test classes results in what I described above:
public class MyExtension implements BeforeAllCallback {
#Override
public void beforeAll(ExtensionContext context) throws Exception {
System.out.println(context.getRoot());
if (context.getRoot().getStore(Namespace.create(MyExtension.class)).get("someIdentifier", String.class) == null) {
context.getRoot().getStore(Namespace.create(MyExtension.class)).put("someIdentifier", "SomeFooString");
} else {
// this is never executed
System.out.println("Found it, no need to store anything again!");
}
}
}
EDIT: Here is a minimal project on GH(link), run by mvn clean install, which displays the behaviour I see.
I just copied your MyExtension verbatim (i.e., with zero changes) and ran both FooTest and BarTest.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
#ExtendWith(MyExtension.class)
class FooTest {
#Test
void test() {
}
}
and
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
#ExtendWith(MyExtension.class)
class BarTest {
#Test
void test() {
}
}
And the result is:
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext#2280cdac
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext#2280cdac
Found it, no need to store anything again!
Thus, getRoot() works as documented.
The only explanation for why you see two different roots is that you must be executing the tests in different processes.
Please keep in mind that the root ExtensionContext instance is bound to the current execution of your test suite.
So if you run FooTest and BarTest one after the other in an IDE, that will actually result in two "test suites" with different roots. The same is true if you configure your build tool to fork between test classes.
Whereas, if you execute both test classes together in a single "test suite" (e.g., by telling your IDE to run all tests in the same package or same source tree) you will then see that there is one root like in the output I provided above.
Note, however, that there was an issue with the junit-platform-surefire-provider prior to version 1.0.3, whereby the provider launched the JUnit Platform for each test class. This would give the appearance of forking even though Surefire did not actually start a new JVM process. For details, see https://github.com/junit-team/junit5/pull/1137.
I'm new to using Command Line Interface. So I just have a question on how to invoke the runner class of the cucumber using CLI technique.
I have a Java program which contains a main method. When testers pass the argument which is test case, it will fetch the feature file. The java program invoke a custom made API which will fetch the correct feature file.
Next I'll have to invoke the Cucumber runner class to execute the test case. I need to pass this particular feature file as the argument. Two questions, Can we invoke the runner class from a different main method. I did some research and I was not able to find a concrete answer.
Two questions,
cucumber.api.cli.Main.main(arguments); So how do i specify the jar location of my runner class.
`FeatureFileCreation.main("xxxxx"); - API that fetches the right feature file
String[] arguments = {"-", ""};
cucumber.api.cli.Main.main(arguments);
How do I specify where my jar is located? How can I pass my feature file?`
Should I create a main method in the runner class, something like this? For the sake of using CLI,Since I need to create a runnable jar. I should have a main method in my runner class.
`
#RunWith(Cucumber.class)
#Cucumber.Options(features="C:/Users/IBM_ADMIN/Desktop/CRAutomation/CR Regression1/src/My.feature",glue={"bell.canada.step.definition"})
public class AutomationRunnerAction {
public void main(){
}
}`
Please note that, Getting the right feature file is 1 java API. I will invoking that API from one main method of one java program. The runner class with step definition and methods are a diff java program.
Unfortunately the accept answer is not correct. If you look at the source of Main.main() you'll notice that it contains: System.exit(exitstatus) which terminates the system.
The proper way to run the commandline programatically would be to use Main.run() like this:
String [] argv = new String[]{ "-g","","./src/main/java/featureDetails/Testing.feature"};
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
byte exitstatus = Main.run(argv, contextClassLoader);
Try this if this works. You do not need any Runner class. Just call the static main method of Main class that corresponds to running cucumber from cli.
public static void main(String[] args) throws Throwable {
//Your code to get feature file full path
Main.main(new String[]{"-g", "classpath to step definition file", "Full path to feature file"});
// My stepdefinition is inside java package at cucumber.sample.test
// My feature file is inside src/test/resources/features/samplethree.feature
}
For additional parameters like tags or plugin use "-t","#Tags". Important the feature file path has to be the last option.
I am running this for Eclipse with Maven setting up classpath and jar dependencies.
I've got some class with property marked as internal.
Then I try to set that property from test code which is in java.
How can I access those properties? test code and class code are in the same package.
example:
class MainActivity : AppCompatActivity() {
interal var someProperty = "test"
}
test code:
#Test
public void firstStartTest() {
val activity = MainActivity()
activity.setSomeProperty("something") //does not compile
}
Android Studio is suggesting activity.setSomeProperty$production_sources_for_module_app();
but this also does not compile.
Both classes (MainActivity and test class) must be in one module. This is a module definition:
More specifically, a module is a set of Kotlin files compiled together:
an IntelliJ IDEA module;
a Maven or Gradle project;
a set of files
compiled with one invocation of the Ant task.
https://kotlinlang.org/docs/reference/visibility-modifiers.html
It means, check your project structure.
add #JvmField annotation.
It treats variable as java protected
There are two ways of doing this:
Make the property protected. Note on how Java & Kotlin treat protected differently. In Java it's possible that other classes in the same package access protected members. Thus your test class (in Java) can access it.
Access the property via its ugly name. It should be sort of like activity.setSomeProperty$production_.... Make use the autocomplete. From the documentation:
Members of internal classes go through name mangling, to make it
harder to accidentally use them from Java and to allow overloading for
members with the same signature that don't see each other according to
Kotlin rules;
How to unit test private (means with package visibility) classed in java?
I have a package, only one class is public in this package, other classes are private. How to cover other classed with unit tests? I would like to include unit tests in resting jar.
Create the unit test class in the same package.
For example, If com.example.MyPrivateClass located in src/main/java/com/example/MyPrivateClass.java
Then the test class will be in same package com.example.MyPrivateClassTestCase and will be located in src/test/java/com/example/MyPrivateClassTestCase.java
There are two ways to do this.
The standard way is to define your test class in the same package of the class to be tested. This should be easily done as modern IDE generates test case in the same package of the class being tested by default.
The non-standard but very useful way is to use reflection. This allows you to define private methods as real "private" rather than "package private". For example, if you have class.
class MyClass {
private Boolean methodToBeTested(String argument) {
........
}
}
You can have your test method like this:
class MyTestClass {
#Test
public void testMethod() {
Method method = MyClass.class.getDeclaredMethod("methodToBeTested", String.class);
method.setAccessible(true);
Boolean result = (Boolean)method.invoke(new MyClass(), "test parameter");
Assert.assertTrue(result);
}
}
As indicated in #Kowser's answer, the test can be in the same package.
In Eclipse, and I assume other IDEs, one can have classes in different projects but in the same package. A project can be declared to depend on another project, making the other project's classes available. That permits a separate unit test project that depends on the production project and follows its package structure, but has its own root directory.
That structure keeps the test code cleanly separated from production code.