我有自动数据系统自动化测试。 试验涉及三个实体:
Data object class - data to be filled in forms. Herein each form on a page could be represented by a different data object.
Helper class - which fills in data in a form on page
Test class - which uses data object and helper class to perform test.
下面是测试的缩略本——
public class ParallelDataObject {
HelperClass helperClass = new HelperClass();
Data data;
@BeforeMethod
public void setTestData() {
data = new Data();
helperClass.setData(data);
}
@Test
public void passM1() {
helperClass.verifyFlag();
}
@Test
public void failM2() {
data.setFlag(false);
helperClass.setData(data);
helperClass.verifyFlag();
}
@Test
public void passM3() {
helperClass.verifyFlag();
}
@Test
public void failM4() {
data.setFlag(false);
helperClass.setData(data);
helperClass.verifyFlag();
}
}
class HelperClass {
Data data;
public void setData(Data data) {
synchronized (data) {
this.data = data;
}
}
public void verifyFlag() {
synchronized (data) {
assert data.getFlag();
}
}
}
class Data {
private boolean flag;
public Data() {
flag = true;
}
public Data setFlag(boolean flag) {
synchronized (this) {
this.flag = flag;
return this;
}
}
public boolean getFlag() {
synchronized (this) {
return flag;
}
}
When executing methods in parallel I encountered weird results as data is not thread safe. Then I incorporated synchronize blocks but yet I encounter weird results. I am sure I have messed up how synchronization should be used here in. Any insight?
我做了另外一次工作。 我设置了另一类试验,与第一个测试类别完全相同。 我从助手和数据类别删除了所有同步。 当我同时工作时(而不是方法)。 测试结果与预期相同。 当我同时执行课堂时,我为什么不赞成,尽管他们使用同样的助手类别和数据物体?