Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Robolectric Test Runner (can easily be just a regular JUnit Runner) that can execute test methods in specific order.

Usage

Add @Order annotation to your test methods:

@Test
@Order(0)
public void aRandomTestMethod_willBeExecutedFirst() { ... }

@Test
@Order(1)
public void anotherRandomTestMethod_willBeExecutedSecond() { ... }

Methods that are not annotated with @Order will be executed (in undefined order) after the ones that are annotated.

/*
* Copyright 2017 Bartosz Lipinski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.your.package;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.robolectric.RobolectricTestRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OrderedRobolectricTestRunner extends RobolectricTestRunner {
public OrderedRobolectricTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
@Override
protected List<FrameworkMethod> computeTestMethods() {
final List<FrameworkMethod> unordered = super.computeTestMethods();
List<FrameworkMethod> otherMethods = new ArrayList<>(unordered);
List<FrameworkMethod> orderedMethods = new ArrayList<>();
// extracting methods annotated with Order
for (int i = 0; i < otherMethods.size(); i++) {
FrameworkMethod frameworkMethod = otherMethods.get(i);
Order order = frameworkMethod.getAnnotation(Order.class);
if (order != null) {
orderedMethods.add(frameworkMethod);
otherMethods.remove(i--);
}
}
// sorting ordered methods
Collections.sort(orderedMethods, (f1, f2) ->
f1.getAnnotation(Order.class).value() -
f2.getAnnotation(Order.class).value());
// appending other methods to ordered methods
orderedMethods.addAll(otherMethods);
return Collections.unmodifiableList(orderedMethods);
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Order {
int value();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.