如何在JUnit测试之间共享状态? [英] How do I share state between JUnit tests?
问题描述
我有一个扩展了junit.framework.TestCase
的测试类,其中有几种测试方法.每个方法都打开与服务器的HTTP连接并交换请求和响应json字符串.一个方法使用名为UID(类似于sessionId)的字符串获取响应,我需要在对服务器的后续请求中使用.
我以前是将该字符串写入文件,下一个请求是读取该文件中的字符串.我一次运行一个方法.现在,我试图不使用文件操作就使用该字符串.我维护了一个hastable(因为在那里为此,在我的测试类中有很多要作为实例变量进行跟踪的UID,但最终发现每次执行静态块时,每次调用方法时都会为我的类加载该类,这导致这些UID丢失. /p>
如何在不写入文件和不读取文件的情况下实现这一目标?
我怀疑标题是否符合我的要求.请相应地对其进行编辑.
为此您将需要一个静态变量,因为每个测试都具有自己的测试类实例.
使用此模式:
private static String uuid;
private void login() {
// Run this only once
if (null != uuid) return;
... talk to your server ...
uuid = responseFromServer.getUuid();
}
@Test
public void testLogin() {
login();
assertNotNull( uuid );
}
@Test
public void someOtherTest() {
login();
... test something else which needs uuid ...
}
@Test
public void testWithoutLogin() {
... usual test code ...
}
这种方法可确保为需要它的每个测试调用login()
,并对其进行了单独测试,并且您可以独立运行每个测试.
I have a test class extending junit.framework.TestCase
with several test methods.Each method opens a HTTP connection to server and exchange request and response json strings.One method gets a response with a string called UID(similar to sessionId) which i need to use in subsequent requests to the server.
I was previously writing that string to a file and my next requests read that file for string.I am running one method at a time.Now I am trying to use that string without file operations.I maintained a hastable(because there are many UIDs to keep track of) in my test class as instance variable for the purpose , but eventually found that class is getting loaded for my each method invocation as my static block is executing everytime.This is causing the loss of those UIDs.
How do I achieve this without writing to file and reading from it?
I doubt whether my heading matches my requirement.Someone please edit it accordingly.
You will need a static variable for this because each test gets its own instance of the test class.
Use this pattern:
private static String uuid;
private void login() {
// Run this only once
if (null != uuid) return;
... talk to your server ...
uuid = responseFromServer.getUuid();
}
@Test
public void testLogin() {
login();
assertNotNull( uuid );
}
@Test
public void someOtherTest() {
login();
... test something else which needs uuid ...
}
@Test
public void testWithoutLogin() {
... usual test code ...
}
This approach makes sure that login()
is called for each test that needs it, that it's tested on its own and that you can run each test independently.
这篇关于如何在JUnit测试之间共享状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!