Trouble with JUnit - java

Whenever I create a new JUnit Test Case it generates like this:
import junit.framework.TestCase;
public class Test extends TestCase {
}
But this isn't correct. There isn't even an #Test generated, and when I put it in myself I get a type mismatch error (cannot convert from Test to annotation). Any help?
Edit:
import static org.junit.Assert.*;
public class Test {
#org.junit.Test
public void test() {
fail("Not yet implemented");
}
}

You are not using the right version of JUnit. Check the version you are using. Annotations are available in JUnit 4 and not available in JUnit 3

Related

(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.

installation of JUnit on ecllipse

I have downloaded ecllipse kepler - latest version from ecllipse website.
I downloaded junit 4.10 jar file from sourseforge website (did not get a copy on github)
After opening ecllipse i added my jar file as external jars (it was successfully added)
I imported by saying "import static org.junit.Assert.*;"
then for the testing method i wrote on the top #Test then followed by method definition
Now ecllipse is poping me an error for #Test that -- "cannot convert from test to annotation" and it not even giving me an option to run my class as JUnit test.
Am I missing any step somewhere?
I am pasting my code here :
package test;
import static org.junit.Assert.*;
public class Test {
#Test
public static void main(String[] args) {
// TODO Auto-generated method stub
assertEquals(0, voidMethod(), 0);
}
static int voidMethod()
{
return 0;
}
}
Thanks in advance
You need to import the junit Test class. Use this:
import org.junit.Test;
It would also be best to name your method something other than Test so as not to conflict with this import.
Also, you can't use a static method as a Junit test method and your Junit tests shouldn't have arguments. You will get an exception stating that the test method should not be static, and the test method should not take parameters.
The whole point of Junit Tests is that you have many individual tests that can be run independently of each other. You don't have any arguments passed into the test. Everything you need should be set up in the test or before the test using one of the #Before annotations.
Try something like this:
package test;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestClass {
#Test
public void myTestMethod() {
// TODO Auto-generated method stub
assertEquals(0, voidMethod(), 0);
}
static int voidMethod()
{
return 0;
}
}
unfortunately I had put same name to my class as 'Test' which was actually crating problems..
Thanks a lot...

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.

How do I use JUnitPerf with JWebUnit and JUnit 4?

I have a series of functional tests against a web application that correctly run, but each require the class level setup and teardown provided with the #BeforeClass and #AfterClass annotations, and hence require JUnit 4.0 or above.
Now I want to perform load testing using a small number of these functional tests, which simulate a large number of users requesting the related page of the web application. In order for each user to have their own "simulated browser" in JWebUnit, I need to use a TestFactory in JUnitPerf to instantiate the class under test, but since JUnit 4 tests are annotated with #Test instead of being derived from TestCase, I'm getting a TestFactory must be constructed with a TestCase class exception.
Is anyone successfully using JUnitPerf and its TestFactory with JUnit 4? And what is the secret sauce that lets it all work?
You need a JUnit4 aware TestFactory. I've included one below.
import junit.framework.JUnit4TestAdapter;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.clarkware.junitperf.TestFactory;
class JUnit4TestFactory extends TestFactory {
static class DummyTestCase extends TestCase {
public void test() {
}
}
private Class<?> junit4TestClass;
public JUnit4TestFactory(Class<?> testClass) {
super(DummyTestCase.class);
this.junit4TestClass = testClass;
}
#Override
protected TestSuite makeTestSuite() {
JUnit4TestAdapter unit4TestAdapter = new JUnit4TestAdapter(this.junit4TestClass);
TestSuite testSuite = new TestSuite("JUnit4TestFactory");
testSuite.addTest(unit4TestAdapter);
return testSuite;
}
}

Categories

Resources