Order of evaluation of multiple #Test annotation inside a class in Junit - junit

Can anyone tell me what is the order of evaluation of #Test annotation in Junit when you have multiple #Test Annotation?
I was trying with the following example but didnot find any specific order.You may consider the following example to explain your answer.
package test_Cases;
import org.junit.Test;
public class First_test_case {
#Test
public void apsTest(){
System.out.println("THIS IS FIRST TEST CAES.");
//selenium code
}
#Test
public void appletestTest(){
System.out.println("THIS IS second TEST CAES.");
//selenium code
}
#Test
public void aboutestTest(){
System.out.println("THIS IS third TEST CAES.");
//selenium code
}
#Test
public void dtestTest(){
System.out.println("THIS IS fourth TEST CAES.");
//selenium code
}#Test
public void etestTest(){
System.out.println("THIS IS fifth TEST CAES.");
//selenium code
}#Test
public void ftestTest(){
System.out.println("THIS IS sixth TEST CAES.");
//selenium code
}
}

Using #FixMethodOrder JUnit annotation we can achieve ordered execution of the junit tests
Note: We need to use JUnit 4.11 or later versions to get this option
Example Code Snippet:
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
// Test execution order : ascending order of method names
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderedJUnitTest {
#Test
public void second() {
System.out.println("Inside second test");
}
#Test
public void first() {
System.out.println("Inside first test");
}
#Test
public void third() {
System.out.println("Inside third test");
}
}
Output:
Inside first test
Inside second test
Inside third test
Similarly we can use #FixMethodOrder(MethodSorters.DEFAULT) and #FixMethodOrder(MethodSorters.JVM) as well which will order the test execution.
Visit https://github.com/junit-team/junit/wiki/Test-execution-order to get more insight on this.

Related

Override Mockito statements in local function doesn't work with PER CLASS mode?

I'm new to JUnit5 and I noticed something weird happening.
Let's see it with an example,
I have a source class named A
class A {
someDownStreamService service;
void printer() {
int getData = service.getIntegerData();
print(getData);
}
}
Now when I wrote test case,
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
class JUnit5TestCaseForClassA {
#Mock
private someDownStreamService service;
#InjectMocks
private A a;
#BeforeEach
setUp() {
initMocks(this);
Mockito.when(service.getIntegerData()).thenReturn(25);
}
#Test
void test1() {
a.printer();
}
#Test
void test2() {
Mockito.when(service.getIntegerData()).thenReturn(19);
a.printer();
}
}
When I trigger test2() individually, the printer() function is printing 19 as I suppose Mockito.when() statement is overridden to return 19 in test2() function over what was registered in #BeforeEach to return 25.
And when I execute all the test classes under class 'JUnit5TestCaseForClassA', I see that printer() function is printing 25 for both these test function's. Is the overriding not happening? Or what is the issue?
Why is this discrepancy?????
I can see making #TestInstance(TestInstance.Lifecycle.METHOD), will resolve the issue, as each testcases are triggered with new test instance. But I want to test with Lifecycle.PER_CLASS.
I have slightly modified your example to make it testable (with assertions) as follows.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.mockito.InjectMocks;
import org.mockito.Mock;
#TestInstance(Lifecycle.PER_CLASS)
public class MockitoJUnitJupiterTestCase {
#Mock
MyService service;
#InjectMocks
A a;
#BeforeEach
void setUp() {
initMocks(this);
when(service.getData()).thenReturn(25);
}
#Test
void test1() {
assertEquals("data: 25", a.printer());
}
#Test
void test2() {
when(service.getData()).thenReturn(19);
assertEquals("data: 19", a.printer());
}
}
interface MyService {
int getData();
}
class A {
MyService service;
String printer() {
return "data: " + service.getData();
}
}
When I execute that using Mockito 2.23.4 or 2.28.2 and JUnit Jupiter 5.5 snapshots, the tests pass.
Can you try out this variation of your tests and let us know if both tests pass when executing the entire test class?

mockito unit testing Wanted but not invoked:

I have seen there are similar question already exist in SO , I tried all the solution , but couldn't fix my problem , as I am new to tdd
I have a class like this
public class AppUpdatesPresenter {
public void stopService() {
ServiceManager.on().stopService();
}
}
I have the test class like this
#RunWith(MockitoJUnitRunner.class)
public class AppUpdatesPresenterTest {
#Mock
AppUpdatesPresenter appUpdatesPresenter;
#Mock
ServiceManager serviceManager;
#Mock
Context context;
#Test
public void test_Stop_Service() throws Exception {
appUpdatesPresenter.stopService();
verify(serviceManager,times(1)).stopService();
}
}
When I tried to test that , if I call stopService() method , then ServiceManager.on().stopService(); called at least once .
But I am getting the following error
Wanted but not invoked:
serviceManager.stopService();
-> at io.example.myapp.ui.app_updates.AppUpdatesPresenterTest.test_Stop_Service(AppUpdatesPresenterTest.java:103)
Actually, there were zero interactions with this mock.
Not sure whats gone wrong .
When you call appUpdatesPresenter.stopService();, nothing happened as you didn't tell it what should be happened.
To make your test pass, you need stubbing the appUpdatesPresenter.
#Test
public void test_Stop_Service() throws Exception {
doAnswer { serviceManager.stopService(); }.when(appUpdatesPresenter).stopService()
appUpdatesPresenter.stopService();
verify(serviceManager).stopService();
}
Btw, the above test is meaningless as you stub all the things.
To make the test case meaningful, you should inject the ServiceManager instead of coupling it with AppUpdatePresenter.
public class AppUpdatesPresenter {
private final ServiceManager serviceManager;
public AppUpdatesPresenter(ServiceManager serviceManager) {
this.serviceManager = serviceManager;
}
public void stopService() {
sm.stopService();
}
}
Then make the AppUpdatesPresenter under test.
#InjectMock AppUpdatesPresenter appUpdatesPresenter;
Now the test case doesn't rely on canned interaction but real implementation of your code.
#Test
public void test_Stop_Service() throws Exception {
appUpdatesPresenter.stopService();
verify(serviceManager).stopService();
}

How to define only last test method assertion will be involved

I have a two class's for testing regression test. We have in some case more than one test method in the class and in the methods we are usually using assertions. I want to know if there any method is available, to make use #Rule test method only the last method in the class. Here is my code:
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JustOneClass extends ParentClass {
#Rule
public class GeneralRule articleHotspotRule = new class GeneralRule (this);
#Test
aMethod(){
Assert.assertTrue()
}
#Test
bMethod(){
Assert.assertTrue()
}
#Test
cMethod(){
Assert.assertTrue()
}
#Test
dMethod(){
if this assert is failed Assert.assertTrue()
}
}
We have a another class which extends TestWatcher
public class GeneralRule extends TestWatcher {
private ParentClass baseTest;
public GeneralRule (final GeneralRule generalRule) {
this.baseTest = generalRule;
}
#Override
protected void failed(final Throwable e, final Description description) {
baseTest.after();
}
}
in this case I want that baseTest.after() will be used only if assertion of dMedthod is failed.
Rather than using a rule to try and check for the failure, how about checking for the failure condition and then fail the test programatically? Certainly not as elegant or reusable as a rule but may satisfy your requirement.
#Test
public void dMethod() {
...
if(actual == false) { // check for failure scenario
after(); // call the after method
Assert.fail("hello failure"); // programatically fail the test
}
}

TestSuite JUnit -> Each TestCase has same #Before etc

I'm just writing som Selenium WebDriver tests with JUnit 4.
Test Cases are grouped by JUnit TestSuite. Each test case (test class) has the same #Rule #BeforeTest #AfterTest
How can i realize this in JUnit TestSuite, so that I don't have the same code for #Rule, #BeforeTest and #AfterTest in each test case (class)?
//edit: maybe i define an abstract testcase class, which i extend from each test case?
You could merge the code of #Rule, #BeforeTest and #AfterTest into a single rule.
public class TheMergedRule implements TestRule {
private final TestRule theCurrentRule = ...
public Statement apply(final Statement base, final Description description) {
return new Statement() {
theCodeOfBefore();
theCurrentRule.apply(base, description);
theCodeOfAfter();
}
}
public void theCodeOfBefore() {
...
}
public void theCodeOfAfter() {
...
}
}

How to have individual SetUp functions in Junit

I have two test functions and for each I want to have different #Before methods. How to achieve this ?
Although it seems to be convenient to organize all the test under the same class, for your case I think the best option is to separate the tests into different classes, each one with his corresponding setUp.
An alternative (I prefer the previous option) could be call the setUp directly in your test method, like the example as follows:
public class FooTest {
public void setUpMethod1() {
// do setUp things
}
public void setUpMethod2() {
// do setUp things
}
#Test
public void testMethod1() {
setUpMethod1();
// Test
}
#Test
public void testMethod2() {
setUpMethod2();
// Test
}
}
Only as a curiosity (IMO not recomended for your case), you can override the default junit RunListener with your own implementation. Method testStarted is executed before every test and you have access to class and methodName to be able to identify the running test. Dummy sample:
public class MyRunListener extends RunListener {
#Override
public void testStarted(Description description) throws Exception {
//...
Class testClass = description.getClass();
String methodName = description.getMethodName();
//...
}
}
Hope it helps.