【问题标题】:Testing a method which modifies the field of the mocked class测试修改模拟类字段的方法
【发布时间】:2017-04-10 15:06:31
【问题描述】:

已经问了很多问题,但对于我的具体案例没有真正有用的信息。

我想测试一个方法,它在 A 类中,它是一个 void,它从 B 类调用一些方法,然后修改或检查它的字段 - 多个。

这是一个例子:

public class A {
private B b;

public A(B b){
    this.b = b;
}

public void checkStageOne(Worksheet ws){
    if( long statement){
        if(B.checkStorage(ws)){
            ws.setThing("Nasty");
        }
        else { ws.setStatus("Not so nasty"); }
    }
}

假设 LinkedLists 以某种方式被填满。 A 类 checkStageOne() 的参数包含在 B 类的列表中。

public class B {
private LinkedList<Worksheet> sheetList = new LinkedList<>();
private LinkedList<UsedParts> upList = new LinkedList<>();
private LinkedList<UsedParts> matList = new LinkedList<>();


public boolean checkStorage(int id){
     for(UsedParts up : upList){
        if(up.getSheetID()== id){
            for(Material mat : matList){
                if(up.getMatID() == mat.getMatID()){
                    if(mat.getQuantity() - up.getQuantityNeeded() < 0){
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

我想模拟 B 类,但我完全不知道如何伪造 B 的字段,然后甚至在它们上测试结果。我所知道的是我可以用 EasyMock.expectLastCall(); 来测试一个 void;但随后我需要检查它是否真的与断言有关。

你有什么建议吗?

VBR, 突击猪

【问题讨论】:

  • 您可以为 B 创建接受 3 个linkedLists 的构造函数,然后使用 mockito 为您的 B 测试实例创建:LinkedList mock1 = mock(LinkedList.class); LinkedList mock2 = mock(LinkedList.class); LinkedList mock3 = mock(LinkedList.class);新 B(模拟 1,模拟 2,模拟 3);然后您可以检查是否与这些模拟进行了交互
  • 谢谢,这是个好主意。你知道如何在 EasyMock 中检查吗?

标签: java junit field void easymock


【解决方案1】:

要回答您的评论,您可以使用 EasyMock 做同样的事情。

但是我想嘲笑B,那么,那不是你应该做的。只是模拟B。然后,你只关心checkStorage 返回truefalse 来测试A

类似这样的:

B b = mock(B.class);
Worksheet ws = mock(Worksheet.class);
A a = new A(b);
expect(b.checkStorage()).andReturn(true); // expect one call to checkStorage to return true
ws.setThing("Nasty"); // expect setThing to be called

replay(b, ws);

a.checkStageOne(ws); // will call checkStorage that will return true

verify(b, ws); // will make sure setThing was called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2015-12-17
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多