How to temporarily disable a Junit test from running? - java

I have the following Junit test class
package Md5Tests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import timebackup.*;
/**
*
* #author jack
*/
public class PathNodeToXmlTest {
public PathNodeToXmlTest() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
#Test
public void createXml() {
PathNode root = new PathNode(true, "docs", "0");
root.addPathNode(new PathNode(true, "docs sub folder", "1"));
root.addPathNode(new PathNode(false, "docs sub file", "2"));
PathNodeToXml xmlCreator = new PathNodeToXml(root);
System.out.println(xmlCreator);
}
}
I am now trying to temporarily stop the test createXml() from being run by the test runner. I have tried adding the #Ignore annotation right before the #Test annotation however the compiler throws an error saying that it can't find the symbol for #Ignore. I am using the NetBeans Ide.
Anyone have any ideas either how to prevent the compile error, or another way to temporarily prevent a JUnit test from running?

#Ignore annotation is in a package org.junit so you need to add import statement
import org.junit.Ignore;
or
import org.junit.*;
Next time you have a problem like this you can just google class name (e.g. junit #Ignore) go to the documentation page and check package name.
In NetBeans you can use "Source -> Fix Imports" command (Ctrl + Shift + I) and IDE will try to resolve necessary imports automatically.

Related

How execute code after each dynamic test?

There is a test:
package com.cdek.qa_auto.config;
import com.cdek.qa_auto.utils.CdekJUnitListener;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
/***
*
*/
#SpringBootTest
public class JUnit5Test {
public JUnit5Test() throws Exception {}
#BeforeEach
public void beforeEach() throws Exception {
Launcher launcher = LauncherFactory.create();
TestExecutionListener listener = new CdekJUnitListener();
launcher.registerTestExecutionListeners(listener);
}
#TestFactory
public Stream<DynamicTest> test() throws Exception {
List<String> list = new ArrayList<>();
list.add("1");
list.add("12");
list.add("123");
list.add("1234");
list.add("12345");
return list.stream().map(item -> (
dynamicTest("test_" + item, () -> {
if ("1".equalsIgnoreCase(item)) {
System.out.println("fail");
fail("fail");
} else if ("12".equalsIgnoreCase(item)) {
assertTrue(false);
} else if ("123".equalsIgnoreCase(item)) {
throw new Exception("msg");
} else {
assertTrue(true);
}
}
)));
}
}
For example, make a screen for fallen tests.
Written implementation of import org.junit.platform.launcher.TestExecutionListener.
Connect so normally did not work. Does not go into executionFinished.
Basis: JUnit5-Maven-SpringBoot
How do execute specific code after each dynamic test?
As stated in the JUnit 5 User Guide:
The execution lifecycle of a dynamic test is quite different than it
is for a standard #Test case. Specifically, there are no lifecycle
callbacks for individual dynamic tests. This means that #BeforeEach
and #AfterEach methods and their corresponding extension callbacks are
executed for the #TestFactory method but not for each dynamic test. In
other words, if you access fields from the test instance within a
lambda expression for a dynamic test, those fields will not be reset
by callback methods or extensions between the execution of individual
dynamic tests generated by the same #TestFactory method.
Thus, you cannot use an #AfterEach method or one of the "after" lifecycle callback extensions (i.e., AfterEachCallback or AfterTestExecutionCallback).
Depending on what you are trying to achieve in your "listener", you may be able to accomplish that in a TestExecutionListener, but you cannot register that from within the test class. See Plugging in your own Test Execution Listener in the User Guide for details.

(JUnitCore.runClasses ) How Junit file is processed by 'Main' class in Java?

Junit Test Case file Below
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
#Test
public void testAdd() {
String str= "Junit is working fine";
assertEquals("Junit is working fine",str);
}
}
================================================================
Main Class File Below
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(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Above code is working fine.
Please let me know how the main class is processing the Junit file.
I cannot understand the main class .
Please explain
It's using reflection. TestJUnit.class is the Class object representing your TestJUnit class. This object allows getting the metadata about the class: its name, its base class, its methods, annotations on the methods, etc.
So, basically, JUnitCore looks for all the public void methods without argument annotated with #Test, and executes them. If one of the method throws an unexpected exception, it's an error. If one of the methods makes an assertion fail, it's a failure, and if the method complete normally, it's a success.

Static mock not working

I have the following sample unit test that tries to mock java.nio.file.Files but this mock does not work and the code attempts to delete the sample path.
#Test
public void testPostVisitDirectory() throws Exception {
Path mockedPath = Paths.get("sample path");
PowerMockito.mockStatic(Files.class);
PowerMockito.doNothing().when(Files.class,
PowerMockito.method(Files.class, "delete", Path.class));
DeleteDirVisitor visitor = new DeleteDirVisitor(false);
Assert.assertEquals("The was a problem visiting the file",
FileVisitResult.CONTINUE,
visitor.postVisitDirectory(mockedPath, null));
}
Any idea what is wrong?
this is the content of the method visitor.postVisitDirectory
[...]
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
[...]
Thanks,
I had a similar problem using powermock 1.5.1 and the Files class and suspect it has a problem static mocking some/all jdk1.7 classes, although I don't know why. I also checked javassist version and at the time it was latest (3.18.0-GA),
I stripped my class under test to just the Files line and it still did not work. I then decided to try to mock another static class, StringUtils.chop("string"); (commons-lang3) and then my powermock test worked and I was able to force it to generate an exception from mock.
This proved to me that I'd done everything by the book and that static mocking didn't work on Files class but it did on StringUtils.
By the way I changed, both, the #PrepareForTest and the PowerMockito.mockStatic() calls to reference the correct class.
In the end I gave up mocking Files. Just a heads-up in case anyone else has the same problem.
EDIT. Got it working: I have since tried this again as I needed it in another project. There is a newer version of PowerMock out (1.5.3) which uses an updated javassist (3.18.1-GA) that fixes a bug I mentioned in my response to another comment.
I can consistently get mocking of Files to work by adding the class under test to #PrepareForTest as well as Files now even if the class you are testing does not expose static methods. I hadn't needed to do this before for other static mocking. I don't know why it's needed or works differently for Files.
Example:
public class MyTestClass {
public void justToTestMocking(Path path) throws IOException {
if (!Files.exists(path)) {
throw new IllegalArgumentException("I know there is a deleteIfExists() but I am just testing mocking");
}
Files.delete(path);
}
}
And the test below:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Files.class, MyTestClass.class})
public class MyTestClassTest {
#Before
public void setUp() {
mockStatic(Files.class);
}
#Test
public void justToTestMocking_WillDeletePath() throws IOException {
Path path = mock(Path.class);
MyTestClass test = new MyTestClass();
when(Files.exists(path)).thenReturn(true);
test.justToTestMocking(path);
verifyStatic();
Files.delete(path);
}
}
Did you add
#RunWith(PowerMockRunner.class)
#PrepareForTest(Files.class)
to your junit test class containing that method?
See powermock docs, the Writing tests section.
EDIT:
Hmmm, it seems like you're doing everything right. Here's what I'm running:
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Files.class)
public class TestVisitor {
public class PrintingVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
#Test
public void testPostVisitDirectory() throws Exception {
final Path mockedPath = Paths.get("sample path");
/* Mocking */
PowerMockito.mockStatic(Files.class);
PowerMockito.doNothing().when(Files.class, PowerMockito.method(Files.class, "delete", Path.class));
/* End Mocking */
final PrintingVisitor visitor = new PrintingVisitor();
Assert.assertEquals("The was a problem visiting the file", FileVisitResult.CONTINUE, visitor.postVisitDirectory(mockedPath, null));
}
}
If I comment out the section labeled Mocking I get the NoSuchFileException. If I leave it, the test passes.
Perhaps post complete example which produces the error?
I had a similar issue and it turns out that it was related to preparing the correct classes.
In the example above the class that was tested was already in the "prepareFor-Scope" because it was an inner class of the test class.
You have to add the classes to #PrepareForTest that call the static methods ... and in my case these was not sufficient because the code that accessed Files.deletewas inside an anonymous class that cannot be explicitly prepared.
I named the anonymous class and added it to #PrepareForTest and everything worked

How to use new JUnit 4.11 features including change test name and set execution order

I am trying to use JUnit 4.11 to set execution order.
I have tried running the Parameterized test example on this link (Changing names of parameterized tests) within Ecipse IDE and I see no change to the displayed test name in Eclipse IDE. I expect to see test names displayed like test[1: fib(1)=1] and test[4: fib(4)=3], but instead they are displayed like test[0] and test[1]
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
The following example running in Eclipse IDE results in the following execution order (b,a,d,c) instead of the expected (a,b,c,d)
package com.org;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExecutionOrderTestName {
#Test
public void bTest() {
System.out.println("b");
}
#Test
public void aTest() {
System.out.println("a");
}
#Test
public void dTest() {
System.out.println("d");
}
#Test
public void cTest() {
System.out.println("c");
}
}
The ordering of tests is not happening, what am I doing wrong?
This sounds like you have another JUnit on the classpath. See if you have, and remove it. In Eclipse, you can look at Project Properties-> Java Build Path, then the Libraries tab.

Use of #Parameters annotation in junit 4.11-SNAPSHOT

I want to make use of the new functionality in the latest build of junit in order to name my parameterized tests
I have the following two tests written in java & scala, but the scala test generates a compiler error:
error: unknown annotation argument name: name #Parameters(name =
"{0}") def data: util.Collection[Array[AnyRef]] =
util.Arrays.asList(Array("x"), Array("y"), Array("z"))
What is the difference in implementation causing this error?
java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.fail;
#RunWith(Parameterized.class)
public class ParameterizedTest {
#Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[]{"x"}, new Object[]{"y"}, new Object[]{"z"});
}
#Test
public void foo() {
fail("bar");
}
}
scala
import java.util
import org.junit.Assert._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized._
#RunWith(classOf[Parameterized])
class ParameterizedScalaTest {
#Test def foo() {
fail("bar")
}
}
object ParameterizedScalaTest {
#Parameters(name = "{0}") def data: util.Collection[Array[AnyRef]] = util.Arrays.asList(Array("x"), Array("y"), Array("z"))
}
Because #Parameters is defined as an inner, you seem to need to give the full name.
Try
#Parameters(Parameters.name = "{0}")
At least, that is the only significant difference I can observe in the definitions of #Parameters and #Test, and this works:
#Test(timeout = 10)
It turns out the issue here is due to junit-dep.jar being on the classpath through a transient dependency on jMock 2.4.0
Removing that fixed the compiler error, odd that this is an issue for scalac but not javac.

Categories

Resources