I'm working with Arquillian with the JBoss 7 managed container. I'm writing a test to do the following:
Prepare the test locally, not on the JBoss server.
Run the test on the JBoss server.
Validate the output, not on the JBoss server.
Here is my first attempt at this:
#RunWith(Arquillian.class)
public class NotWorking {
#Inject
private Service service;
#Deployment
public static Archive<?> createDeployment() {
// ...
}
#Test
public void testService() throws Exception {
prepare();
service.executeService();
validate();
}
#RunAsClient
public void prepare() throws Exception {
LocalOnlyClass.prepare();
}
#RunAsClient
public void validate() throws Exception {
LocalOnlyClass.validate();
}
}
Unfortunately this doesn't work. Arquillian tries to run the preparation and validation on the server and fails to find the LocalOnlyClass. I can get this to work as follows but its ugly:
#RunWith(Arquillian.class)
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Working {
#Inject
private Service service;
#Deployment
public static Archive<?> createDeployment() {
// ...
}
#Test
#RunAsClient
public void testService1Prepare() throws Exception {
LocalOnlyClass.prepare();
}
#Test
public void testService2Test() throws Exception {
service.executeService();
}
#Test
#RunAsClient
public void testService3Validate() throws Exception {
LocalOnlyClass.validate();
}
}
Does anyone know of a better way to do this that avoids the "fake" tests?
I am not so sure about your comment:
Unfortunately this doesn't work. Arquillian tries to run the
preparation and validation on the server and fails to find the
LocalOnlyClass.
If your problem really lies in where the code gets executed, I don't see how JUnits #FixMethodOrder would make a difference. It just forces a execution order of the tests. The same can be achieved with Arquillian's #InSequence annotation which is what I would recommend in your case.
Related
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)
How can I call tests from another test?
I have a class in the jar that I have added as dependency into my project:
public class Tests{
private MockMvc mockMvc;
#Test
public void test1() throws Exception {
.....
mockMvc.perform(get(myRequest)
.content(dataFromDB)
.......
}
}
#Test
public void test2() throws Exception {
.....
mockMvc.perform(get(myRequest)
.content(dataFromDB)
.......
}
}
.......
And in my project I have:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = MyApp.class)
public class MyTests {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext context;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
#Test
public void test() throws Exception {
CALL SOMEHOW TESTS FROM THE JAR HERE
}
I want those tests from the jar to test my project's database (for example: dataFromDB should be some data from the project where this dependency has been added).
I have already added this jar and I can call class Tests inside my project,so I have access to it. I am just not sure how to run those tests inside it.
What should I change so it works well? Thanks
Updated:
*I want all tests from the jar to call at the same time, not individually.
*I want to give jar access to my db, so it can get all needed testing data in the db table of my project.
From what is see, you have 2 sets of environment, and 1 set of tests.
So one way to solve this is that you make the environment passable, the mockmvc, the dataFromDb, etc, so that the tests can execute independently of the environment.
I would suggest having the test methods in another class, like this very simplified example for easy reading:
class MyTestMethods {
void test1(TestEnv env, Req myRequest) {
env.getMockMvc()
.perform(env.get(myRequest)
.content(env.getDataFromDB());
// assertions here
}
}
class OldTestInJar {
#Test
public void test1() {
new MyTestMethods().test1(myEnv, myReq);
}
}
class MyNewTest {
#Test
public void test1() {
new MyTestMethods().test1(myNewEnv, myNewReq);
}
}
I have the following test class:
#RunWith(Arquillian.class)
public class MyTest {
#Inject
#Uri("mock:repositoryRoute")
private ProducerTemplate producer;
#Inject
#Mock("direct:someStart")
private MockEndpoint endRoute;
#Inject
private ModelCamelContext modelContext;
#Before
public void init() throws Exception {
modelContext.start();
}
#After
public void stopContext() throws Exception {
modelContext.stop();
}
#Deployment
public static Archive<?> deploy() {
// deployment code
}
#Test
public void test1() throws Exception {
endRoute.expectedMessageCount(1);
producer.sendBody("direct:someStart", someBody);
endRoute.assertIsSatisfied();
}
#Test
public void test2() throws Exception {
endRoute.expectedMessageCount(1);
producer.sendBody("direct:someStart", someBody);
endRoute.assertIsSatisfied();
}
}
After I run the test class:
First test passes
Second test fails, even though it goes through the route.
However, if I run the test class with test1 ignored, then test2 passes.
Could someone please explain the reason for this behaviour and advise me how I can fix it?
EDIT
While debugging MockEndpoint and having I have noticed that counter field changes unexpectedly changes from number of tests run to zero while performing one test. So I wonder whether there is one more instance of MockEndpoint created?
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.
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.