Running JUnit does not show anything - junit

In Spring Tool Siute, making an example of use of JUnit, some tests were fine but a new one does not show anything. Is this:
#Test
public void dummyItem_basic() throws Exception {
RequestBuilder request = MockMvcRequestBuilders
.get("/dummy-item")
.accept(org.springframework.http.MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().json("anything........."))
.andReturn();
}
When I click Run JUnit test. JUnit panel only shows Finished after ... seconds.
The console does not show anything neither. Only the label terminated .... but no output returned.
Thank you!

Related

Allure framework isn’t producing detailed reports when using JunitCore

I am running Junit test using JUnitCore.
And i am trying to use allure framework for reporting.
The documentation suggest to add the AllureRunListener using the JUnitCore.addListener().
But, no matter how i try to do so the allure report is coming out empty.
They show the tests that run , and also fail assert, but without the #step,#attachment.
I tried to search for example of using allure report using the JunitCore and not the maven plugin but couldn’t find anything (Running the test using maven work fine, and allure report everything okay).
How it can be done?
The JunitCore runing -
public static void main(String[] args) {
AllureRunListener allureListener =new AllureRunListener();
JUnitCore core = new JUnitCore();
core.addListener(allureListener);
Result result = core.run(BuildNetworkTest.class);
//Result result = core.runClasses(TestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
The test -
#Test
public void BuildNetwork(){
try {
Build buildFactory = new Build();
System.out.println("running the BuildNetwork test in TestRunnerPac.BuildNetwork");
StepTemp();
attachmentTemp();
}catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
#Step
public void StepTemp(){
assertThat("stepTemp").isEqualTo("stepTemp");
System.out.println("In stepTemp..");
}
#Attachment
public String attachmentTemp(){
return "this is an attachmentTemp , hope it will work..";
}
Be sure to launch your tests with the -javaagent argument pointing to aspectjweaver.jar, e.g.:
java -javaagent:"/path/to/aspectjweaver.jar" <the rest of the arguments>
If you're using Maven Surefire plugin, then take a look at the following example on how to do this.

Error in Parameterised test cases in Junit

I am trying to write a parameterized test case in JUnit. My code looks like this:
#RunWith(Parameterized.class)
#PrepareForTest({AR9DirectDebitFileWriterCustomization.class})
public class AR9DirectDebitFileWriterCustomizationTest2 extends AR3BasicUnitTest {
private DirectDebitExtractDetRec mockObj;
private ARApplicationContext mockAppCon;
private AR9DirectDebitFileWriterCustomization spyObj = null;
AccountDBViewData mockdbData;
AccountDBView mockdbView;
SearchInvoicesDBViewData[] mocksearchInvdbviewdatarr = new SearchInvoicesDBViewData[1];
#Before
public void setUp() throws Exception {
AR9DirectDebitFileWriterCustomization ar9Obj = new AR9DirectDebitFileWriterCustomization(mockdbView, mocksearchInvdbviewdatarr, mockdbData);
spyObj = PowerMockito.spy(ar9Obj);
}
public AR9DirectDebitFileWriterCustomizationTest2(DirectDebitExtractDetRec mockObj_from_collection, ARApplicationContext mockAppCon_from_collection) {
this.mockObj = mockObj_from_collection;
this.mockAppCon = mockAppCon_from_collection;
}
#Parameterized.Parameters
public static Collection<Object[]> getparameters() throws ACMException{
return Arrays.asList(new Object[][]{
{mock(DirectDebitExtractDetRec.class),mock(ARApplicationContext.class)}
});
}
#Test
#Parameters
public final void testAddFileRecordCustObjectARApplicationContext( ) throws Exception {
.....SOME CODE
}
Whenever I right click on the testAddFileRecordCustObjectARApplicationContext function and run it as Junit test I get an initialization error :
java.lang.Exception: No tests found matching Method
testAddFileRecordCustObjectARApplicationContext(amdocs.ar.customizationexits.handlers.helpers.AR9DirectDebitFileWriterCustomizationTest2)
from org.junit.internal.requests.ClassRequest#3fa50b at
org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:37)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestMethodReference.(JUnit4TestMethodReference.java:25)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:54)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
After looking for several hours on internet about this issue I could not find anything meaningful. In this scenario I am using spy and powerMocktio Functionality as well.I am not sure what is the root of this error .
And interesting thing is when I run it without using Parameterised test ,it works perfectly fine.
I had very similar error:
No tests found matching data with any parameter from...
According to my observations, it is caused by another strange error:
Unable to mock class ... due to a missing dependency
Only the first I see when I run the test, and the second, when I debug it. According to https://stackoverflow.com/a/23788935/715269,
https://stackoverflow.com/a/25659518/715269, it is the bug connected to classpath reading. The problem disappears, when we upgrade JMockit to higher versions.

Issue with mysql connection while running JUnit test with play2 framework

I'm currently creation JUnit test for a play application. The problem comes when I try to use FakeApplication. I create one in JUnit test but when a test uses the fakeApplication instance, then I got this:
[error] Test controllers.MyClassTest.getMyProperty failed: play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [default]]
Here's my Java code in the JUnit test class:
...
#BeforeClass
public static void startFakeApplication() {
Map<String, String> settings = new HashMap<String, String>();
settings.put("db.default.url", "jdbc:mysql://myhost/releaseDB?characterEncoding=UTF-8");
settings.put("db.default.driver", "com.mysql.jdbc.Driver");
settings.put("db.default.user", "release");
settings.put("db.default.password", "release");
settings.put("db.default.jndiName", "DefaultDS");
Helpers.start(fakeApplication);
}
...
Then my method to test (notice the dummy run so nothing should cause any trouble):
...
public void getMyProperty() {
Helpers.running (fakeApplication, new Runnable() {
public void run() {
}
});
}
...
I think the problem is a database connection issue, and of course when running play in run mode, everything is fine. If I don't use FakeApplication then it's fine also but I need it.
All the database information in startFakeApplication method are coming from conf/application.conf so they're right.
What is strange is that I also have this line in the output screen when running test:
[info] play - datasource [jdbc:mysql://myhost/releaseDB?characterEncoding=UTF-8] bound to JNDI as DefaultDS
Did I missed something important here ?
Thx
Are you passing your settings map to fakeApplication somewhere? Something like:
FakeApplication fakeApplication = fakeApplication(settings);
An alternative option is to have a separate application-test.conf file and include the following in your build.sbt file:
javaOptions in Test ++= Seq(
"-Dconfig.file=conf/application-test.conf"
)
My framework Acolyte provides a JDBC driver & tools, designed for such purposes (mock up, testing, ...): http://acolyte.eu.org
It's used already in some open source projects (Anorm, Youtube Vitess, ...), either in vanilla Java, or using its Scala DSL.
val jdbcUrl = "jdbc:acolyte:anything-you-want?handler=my-unique-id"
val handler = handleStatement.withQueryDetection(...).
withQueryHandler(/* which result for which query */).
withUpdateHandler(/* which result for which update */).
// Register prepared handler with expected ID 'my-unique-id'
acolyte.Driver.register("my-unique-id", handler);
// then ...
Connection con = DriverManager.getConnection(jdbcUrl);
// ... Connection |con| is managed through |handler|
// Or pass the JDBC url to Play config

Thucydides - Test continues after assertion in #Step fails

In the scenario below, I expect that the assertion failure in the step should make the test fail. What I am seeing is that the test continues and since a later assertion in the #Test method fails, the wrong exception is being reported, making it hard to debug.
Is there anyway I can get the test to stop when there is an assertion failure in a #Step?
#Test
public void test() {
....
steps.step1();
System.out.println("test should not reach here");
assertTrue(false);
}
#Step
public void step1() {
assertTrue(false);
}
Tried running the tests from my IDE and maven. (using ThucydidesRunner)
try to check this: http://thucydides.info/docs/thucydides/_creating_a_new_thucydides_project.html
in short words, in steps:
import net.thucydides.core.annotations.Step;
import static org.fest.assertions.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
public class EndUserSteps extends Scenario Steps {
#Step
public void someStep() {
assertThat(true, is(false));
}
}
It turns out the tests don't stop, here is the reply I got from the creators of Thucydides:
"The test can't stop immediately, or it would be impossible to know what steps were not executed, so, yes, this is by design. They do record the first assertion error and then run the steps in "dry-run" mode (no WebDriver calls are made), but that's about the most it can guarantee."

How to get a test's run execution time detail from JUnit's TestResult?

I am new to JUnit, but this is what I am trying to do:
generate data with my DataGenerator class;
instantiate a test class MyTestClass
pass to MyTestClass the test data generated data (first step)
run the test
collect TestResult result
With the above, all works, but I cannot see any timing information (time it took to complete the test) at the TestResult object. Anything being done wrong here ?
The approach above is because I need to run this on other test classes using the same data.
DataGenerator testData = new DataGenerator();
MyTestClass myTestClass = new MyTestClass("mytestmethod");
myTestClass.setBaseLine(testData);
try {
TestResult testResult = myTestClass.run();
System.out.println(testResult.wasSuccessful());
} catch (Throwable ex) {
Logger.getLogger(TestSupervisor.class.getName()).log(Level.SEVERE, null, ex);
}
JUnit 4 has a timeout annotation that will fail the test if the test too long.
//this test will fail if it takes longer than 1 sec
#Test(timeout = 1000)
public void myTest(){
...
}
I think you can get around the DataGenerator issue by using a better TestFixture.
If all of your tests that use the DataGenerator are in the same test class, you can use the #BeforeClass and #AfterClass annotations to set up and tear down data that is used across tests. (those methods with those annotations are called only once before/after all the tests are run).