家伙!我有一个新问题。我使用不同的缓存管理器将一些数据添加到缓存中,并且我正面临着它的问题。我是用junit和spring做的。当我运行测试时,测试方法是随机执行的,但我需要按顺序执行它们。怎么做??这是一些代码和证明控制台输出:
服务类:
@Service("HelloCache")
public class CacheServiceImpl implements CacheInterface {
@Autowired
@Qualifier("memcachedClient")
private MemcachedClient mBean;
public void Add(String key, Object object) {
mBean.set(key, 12, object);
}
public void Get(String key) {
mBean.get(key);
}
public void Delete(String key) {
mBean.delete(key);
}
}
以下是测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "file:src/main/java/spring.xml")
public class UsingMemcachedTest extends TestCase {
@Autowired
@Qualifier("HelloCache")
private CacheInterface emcached;
private byte[][] i = new byte[2500][3000];
private String key = "j";
@Test
public void testAddBulkObjects() {
System.out.println("");
System.out.println("This is async BULK adding test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Add(key+k, i);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya add BULK objects: " + timeE);
System.out.println("");
}
@Test
public void testGetBulkObjects() {
System.out.println("");
System.out.println("This is getting BULK objects test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Get(key+k);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya Get object: " + timeE);
System.out.println("");
}
@Test
public void testDeleteBulkObjects() {
System.out.println("");
System.out.println("This is deleting BULK objects test");
long time = System.currentTimeMillis();
for (int k=1; k<=1000; k++) {
emcached.Delete(key+k);
}
long time2 = System.currentTimeMillis();
long timeE=time2-time;
System.out.println("Vremya delete object: " + timeE);
System.out.println("");
}
输出:
This is deleting BULK objects test
Vremya delete object: 137
This is getting BULK objects test
Vremya Get object: 703
This is async BULK adding test
Vremya add BULK objects: 87681
拜托,帮助! =)
答案 0 :(得分:46)
从版本4.11开始,您可以使用注释指定执行顺序,并按方法名称排序:
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTest {
@Test
public void test1Create() {
System.out.println("first");
}
@Test
public void test2Update() {
System.out.println("second");
}
}
<强> See JUnit 4.11 Release Notes 强>
答案 1 :(得分:9)
JUnit对您的测试运行顺序没有任何承诺。顺序将根据运行测试的环境和上下文而有所不同。
出于这个原因(和其他人),对于影响测试行为的排序,它被认为是非常糟糕的测试设计。你可以使用@Before给你一个干净的石板,然后在特定的测试中进行任何设置作为测试的一部分。
以下问题的接受答案给出了一个很好的解释并链接到一些有用的资源:How to run test methods in specific order in JUnit4?
答案 2 :(得分:4)
JUnit 4.11添加了一些很酷的东西,可以让你控制Test Execution Order