我有类跟随类来测试模拟对象。
public class FordFulkerson {
FlowNetwork network;
Search searchMethod;
public FordFulkerson (FlowNetwork network, Search method) {
this.network = network;
this.searchMethod = method;
}
public boolean compute () {
boolean augmented = false;
while (searchMethod.findAugmentingPath(network.vertices)) {
processPath(network.vertices);
augmented = true;
}
return augmented;
}
protected void processPath(VertexInfo []vertices) {
int v = network.sinkIndex;
// Determine the amount. Goal is to find the smallest
int delta = Integer.MAX_VALUE;
while (v != network.sourceIndex) {
int u = vertices[v].previous;
// Over a forward edge,
int flow;
if (vertices[v].forward) {
flow = network.edge(u, v).capacity - network.edge(u, v).flow;
} else {
flow = network.edge(v, u).flow;
}
if (flow < delta) { delta = flow; }
v = u; // follow reverse path to source
}
// push minimal increment over the path
v = network.sinkIndex;
while (v != network.sourceIndex) {
int u = vertices[v].previous;
if (vertices[v].forward) {
network.edge(u, v).flow += delta;
} else {
network.edge(v, u).flow -= delta;
}
v = u; // follow reverse path to source
}
Arrays.fill(network.vertices, null); // reset for next iteration.
}
}
我的测试:
public class FordFulkersonMockTest {
private FordFulkerson classUnderTest;
private FlowNetwork mockNetwork;
private Search mockSearch;
@Before
public void setUp() {
mockNetwork = createMock(FlowNetwork.class);
mockSearch = createMock(Search.class);
classUnderTest = new FordFulkerson(mockNetwork, mockSearch );
}
@Test
public void test01() {
expect(mockSearch.findAugmentingPath(null)).andReturn(false);
replay(mockSearch);
boolean res = classUnderTest.compute();
assertEquals(false, res);
verify(mockSearch);
}
@Test
public void test02() {
expect(mockSearch.findAugmentingPath(null)).andReturn(true);
try{
Field f = mockNetwork.getClass().getDeclaredField("sinkIndex");
f.setAccessible(true);
f.set(mockNetwork, 0);
f = mockNetwork.getClass().getDeclaredField("sourceIndex");
f.setAccessible(true);
f.set(mockNetwork, 0);
}catch(Exception e)
{
fail(e.getMessage());
}
replay(mockNetwork);
replay(mockSearch);
boolean res = classUnderTest.compute();
assertEquals(true, res);
verify(mockSearch);
}
}
Test01工作正常,但在Test02中我遇到了问题。 在Test02方法中,需要调用processPath。它使用mockNetwork公共最终变量。我不知道在哪里设置它们。它导致了空例外。在代码中,我试图改变对这些字段的可访问性并设置它们,但现在我有错误消息“sinkIndex”。
如何在mockNetwork中模拟公共最终变量? 我正在使用Easymock。
答案 0 :(得分:1)
您说您修改了FlowNetwork
的来源,因此您可以执行以下操作,从而实现更强大的设计和更轻松的测试:
private int sinkIndex
和int getSinkIndex()
)expect(mockNetwork.getSinkIndex()).andReturn(0).anyTimes();
猜猜:mockNetwork.getClass()
正在返回没有状态的cglib EasyMock代理(即没有字段),你可以在调试器中检查它。因此getDeclaredField()
正在返回null
。
如果您真的想使用public
,可以试试FlowNetwork.class.getDeclaredField
。