Here it is my code:
package JUnit;
import org.junit.Test;
public class first {
#Test
public void testOne(){
System.out.println("Executing first test");
}
}
I want to create jar file of this class.Thanks in advance
Related
I am using JUnit 5 and Selenium for my tests.
I need to create a jar file, that when executed, opens the browser and performs the test cases.
I've found from this video: How to Create Runnable Jar File From Selenium Project
that using TestNG you can create an object, set the desired test class and run the test class but I have not found an equivalent way of doing this with JUnit5
I know that with JUnit platform launcher you can use the following code to run test but this does not work when executing the jar file because the JUnit task does not execute the test itself, only captures the output. at least thats what I read from JUnit Launcher Task
public class TestExecutor {
public static void main(String args[]) {
final LauncherDiscoveryRequest request =
LauncherDiscoveryRequestBuilder.request()
.selectors(selectClass(MyTest.class))
.build();
final Launcher launcher = LauncherFactory.create();
launcher.execute(request);
}
}
Is there any way to create an executable jar file that opens the browsers and performs the selenium tests?
1.realize a task timer.(no code,maybe use quaze)
2.realize a web to manual trigger.(use springboot webmvc)
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.FileNotFoundException;
import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
#RestController
#RequestMapping("/excutor")
public class ExcutorContrller {
#GetMapping("/")
public String excute(String packageName, String className) throws FileNotFoundException {
new Thread(() -> {
System.out.println(packageName + "======" + className);
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
.request()
.selectors(
selectPackage(packageName)
// selectClass(com.wusuiwei.cases.JunitTest.class)
)
.filters(
includeClassNamePatterns(".*Test")
)
.build();
Launcher launcher = LauncherFactory.create();
// Register a listener of your choice
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
TestExecutionSummary summary = listener.getSummary();
System.out.println(summary);
// Do something with the TestExecutionSummary.
});
return "excuting....";
}
}
He,everyone! My tests are running by jenkins from general package. Can I set test package in spock which will be runnning first and if in this package will not passed any of test the other tests should be skipped. I saw examples like this:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({TestJunit1.class, TestJunit2.class})
public class JunitTestSuite {
}
But maybe spock has solution where I can use packages instead enum of each classes, because I have many test classes in other many packages.
Also after i used runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
The main thread doesnt stop. I dont know why.
I want to do something like that:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({com.example.test.*.class})
public class JunitTestSuiteFirst {
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({com.example.otherTest.*.class, com.example.otherTests2.*.class})
public class JunitTestSuiteFirst {
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
if(result.wasSuccessful()){
JUnitCore.runClasses(JunitTestSuite.class);
}else {
System.out.println("Build failed");
}
}
}
Or maybe exist more simple solution of this task. Thanks.
Anything you can work out inside your unit testing framework isn't going to be pretty. This is because unit tests are supposed to be independent from each other, with that mindset there won't be strong support for configuring the order of tests. As such your best bet is to look for your solution in your build tools (Ant, Maven, Gradle, etc).
The following gradle snippet sets up 2 different sets/directories of unit tests. With the command gradle test integrationTest build the tests under src/integration will only run if all the tests under src/test pass.
sourceSets {
integrationTest {
java {
srcDirs = ['src/integration']
}
groovy {
srcDirs = ['src/integration']
}
resources.srcDir file('src/integration/resources')
}
test {
java {
srcDirs = ['src/test']
}
groovy {
srcDirs = ['src/test']
}
}
}
I'm trying to use JUnit for my functional testing. Basically I'm doing this to have access to the JUnit reports. Unfortunately I am running into a problem when trying to launch JUnit from a main method.
Basically I am developing a functional testing tool where the user can provide a test filename as a parameter from the command line. I've simplified it a bit below:
import org.junit.runner.JUnitCore;
public class MainClass {
public static void main(String[] args) throws Exception {
TestCase testCase = new TestCase() {
#Override
public String getPath() {
return args[0];
}
};
JUnitCore junit = new JUnitCore();
junit.run(testCase.getClass());
}
}
The TestCase class then acts on the supplied parameter and provides output:
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(TestCase.class);
public String getPath() {
return "etc/Default.flow";
}
#Test
public void testFunc() {
try {
LOGGER.info("Entered testFunc()");
Launcher launcher = new Launcher(getPath());
launcher.launch();
launcher.awaitCompletion();
Assert.assertTrue(launcher.getStatus());
LOGGER.info("Success");
} catch (AssertionError e) {
LOGGER.error("Assertion error", e);
}
}
So from the above, we see that the Launcher instance will be launched with a different filename depending on what was entered on the command line.
The problem is however that Junit is not running my anonymous class. Basically the main method exits without any of the assertions or logging taking place. The TestCase testFunc() method is therefore not called at all.
However, when I change the TestCase instance to not be anonymous, everthing works as expected and the testcase is successful:
import org.junit.runner.JUnitCore;
public class MainClass {
public static void main(String[] args) throws Exception {
TestCase testCase = new TestCase();
JUnitCore junit = new JUnitCore();
junit.run(testCase.getClass());
}
}
Why would JUnit launch the Test class only when it is not anonymous?
If you add listener junit.addListener(new TextListener(System.out)); before running test you will see something like:
There were 2 failures:
1) initializationError(junit.MainClass$1)
java.lang.Exception: The class junit.MainClass$1 is not public.
...
2) initializationError(junit.MainClass$1)
java.lang.Exception: Test class should have exactly one public constructor
at org.junit.runners.BlockJUnit4ClassRunner.validateOnlyOneConstructor(BlockJUnit4ClassRunner.java:158)
at org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassRunner.java:147)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:127)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
It means that JUnit is unable to execute test cases represented by anonymous classes.
I have downloaded the source code of Google App Engine and I would like to change the behavior of some methods (for example, DatastoreService.put(Entity e)) used in this example:
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class LocalDatastoreTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
// run this test twice to prove we're not leaking any state across tests
private void doTest() {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
ds.put(new Entity("yam"));
ds.put(new Entity("yam"));
assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
}
#Test
public void testInsert1() {
doTest();
}
#Test
public void testInsert2() {
doTest();
}
}
The problem is that I do not see that the build.xml file provided with the source code makes any compilation of the source .java files. For example, when I add some garbage to one of the source files and try to build the SDK using ant dist it returns BUILD SUCCESSFUL rather than a compile time error.
Any ideas where can I find the source file of the put(Entity e) method? and how can I compile the source code?
You cannot make any changes to App Engine SDK. SDK exposes methods that are directly related to and dependent upon the internal operations of the App Engine and its Datastore. You are not supposed to compile the SDK separately from your source code.
The documentation for JUnit's TemporaryFolder rule states that it creates files and folders that are
"guaranteed to be deleted when the test method finishes (whether it
passes or fails)"
However, asserting that the TemporaryFolder does not exist fails:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class MyTest {
#Rule
public TemporaryFolder _tempFolder = new TemporaryFolder();
#After
public void after() {
assertFalse(_tempFolder.getRoot().exists()); //this assertion fails!
}
#Test
public void pass() throws IOException {
assertTrue(true);
}
I also see that the file indeed exists on the file system.
Why is this not getting deleted?
This is because JUnit calls after() before it removed the temp folder. You can try to check temp folder in an #AfterClass method and you will see it's removed. This test proves it
public class MyTest {
static TemporaryFolder _tempFolder2;
#Rule
public TemporaryFolder _tempFolder = new TemporaryFolder();
#After
public void after() {
_tempFolder2 = _tempFolder;
System.out.println(_tempFolder2.getRoot().exists());
}
#AfterClass
public static void afterClass() {
System.out.println(_tempFolder2.getRoot().exists());
}
#Test
public void pass() {
}
}
output
true
false
I stumbled upon this question facing the same issue and in my case the cause of the missing deletion was an improper use of the temporary folder.
The toString() method returns the internal folder name, so when trying to create a new file within it, JUnit creates a new folder within the project root.
Adding the getRoot() method solved the issue.
Here's the code I blame:
#Rule
public TemporaryFolder projectFolder = new TemporaryFolder();
//some lines later...
FileUtils.copyFile(deployFile, new File(projectFolder + "/deploy.xml"));
//how I fixed it
FileUtils.copyFile(deployFile, new File(projectFolder.getRoot() + "/deploy.xml"));