I was trying to run a very simple Junit test and i was geeting initialization error.
error page on eclipse
The test method must be a public void method without any argument
#Test
public void sumOfABlankStringIsZero() {
assertEquals(0, Calculator.sum(" "));
}
Related
I have a listener test, where i post a message in a parallel thread and check with LatchCountDownAndCallRealMethodAnswer if the all were processed successfully. Running the test alone, it works perfectly, however if you run all other tests together, it fails because it failed to leave the counter at zero, but the listener received and processed the message normally. Does anyone have any ideas?
My Test Class
#RunWith(SpringRunner.class)
#SpringBootTest
#RabbitListenerTest
#ActiveProfiles("test")
public class EventListenerTest {
EventListener eventListener;
#Autowired
protected RabbitListenerTestHarness harness;
#Autowired
private EventStoreRepository repository;
#SpyBean
private DomainEventPublisher publisher;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DomainRegister.setDomainEventPublisher(publisher);
eventListener = this.harness.getSpy("eventListenerId");
}
#Test
public void storeEventsListenerTest() throws Exception {
LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
doAnswer(answer).when(eventListener).storeEvents(any(BalanceReserved.class));
publisher.publish(new BalanceReserved("12233", 150.0, BigDecimal.ZERO), "");
assertTrue(answer.getLatch().await(10, TimeUnit.SECONDS));
verify(eventListener, times(1)).storeEvents(any(BalanceReserved.class));
}
#After
public void tearDown() {
DomainRegister.setDomainEventPublisher(null);
reset(eventListener);
repository.deleteAll();
}
}
Error
java.lang.AssertionError
If you have other tests using the same queue, you need to shut down the application context for each test so the test's listeners are stopped. By default, the Spring Test framework caches the application context for reuse. This will cause other tests to "steal" messages.
Add #DirtiesContext to each test class that uses #RabbitListeners, to tell the test framework to shutdown the context.
How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:
public int f(int i){
assert i > 0;
return i;
}
I'm using junit 4.12.
You can test it by providing parameter in #Test annotation:
#Test(expected = AssertionError.class)
public void shouldThrowExceptionWhenIncorrectInput() {
f(-3);
}
This will check if the AssertException is thrown.
However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.
To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.
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.
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."
In my webdriver script I have the three methods
setup, test and tearDown
following the junit convention.
In the test method I have few asserts like this
#Test
public void testStudentHome() throws Exception {
String classCode = "I6OWW";
Utilities.studentSignin(driver, baseUrl);
assertEquals(true, sth.openNotification());
assertEquals("My Scores", sth.myScores(true));
}
The sth is the PageObject on which I am performing the tests and that I have created in the setup method.
I am calling all these three methods from a main method like this:
public static void main(String[] args) {
StudentHomeTest sht = new StudentHomeTest();
try {
sht.setup();
sht.testStudentHome();
sht.tearDown();
} catch (Exception ex) {
Logger.getLogger(StudentHomeTest.class.getName()).log(Level.SEVERE, null, ex);
sht.tearDown();
}
}
Now while running the test if some assertion fails the test method should (this is what I expect) throw an exception and the main method should call the tearDown method. But this does not happen. and the browser window continues to stay there.
I am using the netbeans ide for running the test.
following the junit convention
If you follow the jUnit convention, then you will know that teardown methods belong in the #After method as this method will always run after your tests.
create a new method with the #After jUnit annotation.
#After
public void tearDown() {
sht.tearDown();
}
Edit
You know what, I believe that you are running into a classic issue of assertEquals in jUnit.
Stolen from this answer...:
JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).
So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)
--
Instead of using assertEquals on these calls, use assertTrue() instead.
assertTrue(sth.openNotification());
assertTrue("My Scores".equals(sth.myScores(true)));
AssertionError doesn't extend Exception - it's a Throwable.
But in any case, you should have
try {
sht.setup();
sht.testStudentHome();
} finally {
sht.tearDown();
}
No need for a catch block. main can throw Exception.