Why does cucumber run #Before in all glue code files - java

I have a problem with my cucumber tests. It runs the #Before method in
all the glue classes.
For example. This feature file have one glue code in the MainStepDef.class.
#language: en
#run
Feature: Testing a feature
Test before method
Background:
Given stuff is created
Scenario: The test
When i do stuff
Then stuff will be done
The MainStepDef:
public class MainStepDef {
#Before
public void setup() {
System.out.println("This is OK!");
}
#Given("^stuff is created$")
public void stuff_is_created() throws Throwable {
}
#When("^i do stuff$")
public void i_do_stuff() throws Throwable {
}
#Then("^stuff will be done$")
public void stuff_will_be_done() throws Throwable {
}
}
I have an additional glue file called: OtherStep.class
public class OtherStepDef {
#Before
public void setup() {
throw new RuntimeException("No! Bad code! BAD CODE!");
}
#Given("^some other stuff is also created$")
public void some_other_stuff_is_also_created() throws Throwable {
}
}
And finally I have my runner class.
#RunWith(Cucumber.class)
#CucumberOptions(strict = true, tags = {"#run", "~#ignore" },
format = {"html:target/systemtest", "pretty" }, features = "classpath:features/",
glue = {"com.sorkmos.stepdef" }, monochrome = true)
public class RunFeatures {
}
When I run this I get the runtime exception from the OtherStepDef setup method.
Why does this happen? Should it not execute only the glue needed for the feature?
Example project:
https://github.com/cannibalcow/cucumberproblem

This is the intended behaviour of Cucumber: https://groups.google.com/forum/#!topic/cukes/7gILvMsE2Js
This is the intended behaviour of the #Before and #After hooks: they
are not related to each step definition. Every hook is run on each
scenario (unless it's filtered out by tags).

Related

JUnit ClassRule executes code before Spring Boot application shut down

I am running a Spring Boot integration test with org.springframework.boot.test.context.SpringBootTest.
I have written a JUnit 4 org.junit.rules.TestRule and I am using it as a org.junit.ClassRule.
It looks like this:
public class MyRule implements TestRule {
public Statement apply(final Statement statement, Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
// do something
try {
statement.evaluate();
} finally {
// clean up
}
}
};
}
}
Unfortunately, the // clean up code is executed before the Spring Boot context is shut down.
Where do I have to put my code to execute it after the Spring application is shut down?
It seems that the code of all ClassRules is executed first and the Spring context is torn down right before the JVM terminates (see also https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ConfigurableApplicationContext.html#registerShutdownHook--).
When it comes to the tests of spring, I recommend using the Spring test execution listener.
Rules are JUnit's specific feature, and since the spring is integrated with JUnit as a Runner (#RunWith(SpringRunner.class)) they might interfere.
So, back to those test execution Listeners. Basically its a listener managed by Spring itself and it provides hooks to the test life-cycle where you can clean up your code
here is an example:
public class MySampleListener implements TestExecutionListener {
#Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("beforeTestClass");
}
#Override
public void prepareTestInstance(TestContext testContext) throws Exception {
System.out.println("prepareTestInstance");
}
#Override
public void beforeTestMethod(TestContext testContext) throws Exception {
System.out.println("beforeTestMethod");
}
#Override
public void afterTestMethod(TestContext testContext) throws Exception {
System.out.println("afterTestMethod");
}
#Override
public void afterTestClass(TestContext testContext) throws Exception {
System.out.println("afterTestClass");
}
}
If you don't need all the methods, you can use org.springframework.test.context.support.AbstractTestExecutionListener that provides an empty implementation for all these methods.
Now, in the test you supply an annotation #TestExecutionListeners:
#RunWith(SpringRunner.class)
... // stuff like #ContextConfiguration
#TestExecutionListeners(value = {MySampleListener.class, ...})
public class MySampleTest {
#Test
public void testFoo() {
//test me
}
}
If you want to merge the other listeners that spring runs by default, you can use this annotation as follows:
#TestExecutionListeners(value = MySampleListener.class,
mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)

'assert' is ignored on Junit Tests with InstrumentationTestCase

I set up JUnit Test from android unit testing support and get "FAIL" result from the following test class.
public class FooTest extends AndroidTestCase {
#Before
public void setUp() throws Exception { super.setUp(); }
#After
public void tearDown() throws Exception { super.tearDown(); }
#Test
public void testCase1() { assertTrue(false); }
}
However, after replacing 'AndroidTestCase' with 'InstrumentationTestCase', I got "SUCCESS" result in spite of containing assertion that obviously returns 'FAIL'.
I would like to get to know the reason why I had got such a result, which are different by super classes and how to use Context in JUnit framework tests.

running #Test one by one using reflection

I’m trying to run a package with many unit tests (one by one, not as a class) using reflection,
So when I get all the #Test methods that needs to be run I try to do
Result result = new JUnitCore().run(Request.method(Class
.forName(packageAndClass),getTestName()));
But the class returned in packageAndClass has
#Before, #BeforeClass methods (that also might be in its superclass)
So when running the code above I get all the tests running and fail(because some of their values are assigned in the #Before and #BeforeClass methods)
But when running it from eclipse (select the test method name -> right click -> run as -> Junit test)
They all pass (runing together or one by one)
Is there an api of Request that will run the before methods?
Why are you doing that? JUnit is supposed to run the tests for you!
I ran the following test with junit 4.9 :
public class RunOneTest {
public static void main(final String[] args) {
final Result result = new JUnitCore().run(Request.method(RunOneTest.class, "oneTest"));
System.out.println("result " + result.wasSuccessful());
}
#Test
public void oneTest() throws Exception {
System.out.println("oneTest");
}
#Test
public void anotherTest() throws Exception {
System.out.println("anotherTest");
}
#Before
public void before() {
System.out.println("before");
}
#BeforeClass
public static void beforeClass() {
System.out.println("beforeClass");
}
#After
public void after() {
System.out.println("after");
}
#AfterClass
public static void afterClass() {
System.out.println("afterClass");
}
}
and the output was :
beforeClass
before
oneTest
after
afterClass
result true
Are you really sure that the methods are not run ?

Stopping JUnit suite if particular test fails

I have a JUnit test suite in the form:
#RunWith(Suite.class)
#Suite.SuiteClasses( { xx.class, yy.cass })
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
This then calls vanilla tests like this:
public class xxx {
#Test
public void test () throws {
...
I have a situation where I'd like to stop the rest of the test suite running if there's an error or fail in the first test. But errors / fails in the others are ok and the suite should complete as many other tests as it can. Basically the first test failing would indicate it isn't safe to run the rest.
Is this possible?
First you need junit RunListener:
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
public class FailureListener extends RunListener {
private RunNotifier runNotifier;
public FailureListener(RunNotifier runNotifier) {
super();
this.runNotifier=runNotifier;
}
#Override
public void testFailure(Failure failure) throws Exception {
super.testFailure(failure);
this.runNotifier.pleaseStop();
}
}
Then prepare a suite:
public class StopOnFailureSuite extends Suite {
public StopOnFailureSuite(Class<?> klass, Class<?>[] suiteClasses) throws InitializationError {
super(klass, suiteClasses);
}
public StopOnFailureSuite(Class<?> klass) throws InitializationError {
super(klass, klass.getAnnotation(SuiteClasses.class).value());
}
#Override
public void run(RunNotifier runNotifier) {
runNotifier.addListener(new FailureListener(runNotifier));
super.run(runNotifier);
}
}
And run your suite:
#RunWith(StopOnFailureSuite.class)
#Suite.SuiteClasses({
FirstTestClass.class,
SecondTestClass.class,
...
})
What's wrong with calling System.exit()?
If it's first test then consider moving its validation to #BeforeClass and throw exception if it fails. Then only #AfterClass method would run in case of this exception.
Of course, that way you lack all the fixture artifacts created in test setup method(s).
Like your answer but using #Before in an integration test, I did something like this:
public class FooTest {
private static boolean bar;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
bar = false;
}
#Before
public void setUp() throws Exception {
assertTrue(bar);
}
#Test
public void test() {
System.out.println("something");
assertTrue(true);
}
#Test
public void test1() {
System.out.println("Something2");
assertTrue(true);
}
}
Regards!
Based on the answer from Hiro2k (thanks!) I've used the following solution. It's a bit of a hack but it works.
The test which can prevent other tests running goes at the top of the #Suite.SuiteClasses list. That test then has the following:
private static boolean shouldStopRestOfSuite = false;
#Test
public void test () throws Throwable {
try {
... run some test code...
}
catch (Throwable e) {
shouldStopRestOfSuite = true;
throw e;
}
}
Note the above does need to catch Throwable (not exception) so it catches assertion errors. It also re-throws the error so it's logged by JUnit for analysis.
Then there's another test method:
#Test
public void testKillIfNeeded () throws Exception {
if (!shouldStopRestOfSuite) {
return;
}
System.out.println ("Test suite killed due to dangerous error / failure");
System.exit(1);
}
The above is run second and will kill the JUnit process.
Using this method the JUnit test won't end on fail / error if there's an issue but the fail / error is logged for analysis by JUnit and no further tests will run.
Not too pretty but it does the job :)
Firstly you should catch an error and check the same before you run the 2nd test.
#Rule
public ErrorCollector collector = new ErrorCollector();
1. Add Error.
collector.addError(new Throwable("first thing went wrong"));
2. Check before the dependent run.
collector.checkThat(getResult(), not(containsString("ERROR!")));
Reference - ErrorCollector
Are you running tests using ant?
You could write a custom test listener. You can set this in ant http://ant.apache.org/manual/Tasks/junit.html ( enableTestListenerEvents).
I find it troubling that this functionality is so tedious to implement in such a mature library. If you're using JUnit 5 / Jupiter you can use an extension called JUnit Pioneer (https://junit-pioneer.org).
With JUnit Pioneer you can simply add a #DisableIfTestFails annotation to your test class to make all tests stop when one fails.

Run External Command Before JUnit Tests in Eclipse

Is it possible to run an external command before running tests in a given JUnit file? I run my tests using the Eclipse's Run command. Using JUnit 4.
Thanks.
Very vague question. Specifically, you didn't mention how you are running your JUnit tests. Also you mentioned 'file', and a file can contain several JUnit tests. Do you want to run the external command before each of those tests, or before any of them are executed?
But more on topic:
If you are using JUnit 4 or greater then you can tag a method with the #Before annotation and the method will be executed before each of your tagged #Test methods. Alternatively, tagging a static void method with #BeforeClass will cause it to be run before any of the #Test methods in the class are run.
public class MyTestClass {
#BeforeClass
public static void calledBeforeAnyTestIsRun() {
// Do something
}
#Before
public void calledBeforeEachTest() {
// Do something
}
#Test
public void testAccountCRUD() throws Exception {
}
}
If you are using a version of JUnit earlier than 4, then you can override the setUp() and setUpBeforeClass() methods as replacements for #Before and #BeforeClass.
public class MyTestClass extends TestCase {
public static void setUpBeforeClass() {
// Do something
}
public void setUp() {
// Do something
}
public void testAccountCRUD() throws Exception {
}
}
Assuming you are using JUnit 4.0, you could do the following:
#Test
public void shouldDoStuff(){
Process p = Runtime.getRuntime().exec("application agrument");
// Run the rest of the unit test...
}
If you want to run the external command for every unit test, then you should do it in the #Before setup method.

Categories

Resources