我已经阅读过各种关于模拟和测试中存根的文章,包括Martin Fowler的Mocks Are Not Stubs,但仍然不明白其中的区别.
如何用void返回类型模拟方法?
我实现了一个观察者模式,但我无法用Mockito模拟它,因为我不知道如何.
我试图在互联网上找到一个例子,但没有成功.
我的班级看起来像
public class World {
List<Listener> listeners;
void addListener(Listener item) {
listeners.add(item);
}
void doAction(Action goal,Object obj) {
setState("i received");
goal.doAction(obj);
setState("i finished");
}
private string state;
//setter getter state
}
public class WorldTest implements Listener {
@Test public void word{
World w= mock(World.class);
w.addListener(this);
...
...
}
}
interface Listener {
void doAction();
}
Run Code Online (Sandbox Code Playgroud)
系统不会通过模拟触发.=(我想显示上面提到的系统状态.并根据它们做出断言.
我知道我如何使用这些术语,但我想知道是否有单独测试的伪造,模拟和存根的可接受定义?你如何为你的测试定义这些?描述您可能使用每种情况的情况.
以下是我如何使用它们:
假:一个实现接口但包含固定数据而没有逻辑的类.根据实施情况,简单地返回"好"或"坏"数据.
Mock:一个实现接口的类,允许动态设置值以返回/异常从特定方法抛出,并提供检查是否已调用/未调用特定方法的功能.
存根:类似于模拟类,但它不提供验证方法是否已被调用/未调用的能力.
模拟和存根可以由模拟框架手动生成或生成.伪造的类是手工生成的.我主要使用模拟来验证我的类和依赖类之间的交互.一旦我验证了交互并且正在通过我的代码测试备用路径,我就会使用存根.我主要使用假类来抽象出数据依赖性,或者每次使用模拟/存根都太繁琐.
我有一个被调用两次的方法,我想捕获第二个方法调用的参数.
这是我尝试过的:
ArgumentCaptor<Foo> firstFooCaptor = ArgumentCaptor.forClass(Foo.class);
ArgumentCaptor<Foo> secondFooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar).doSomething(firstFooCaptor.capture());
verify(mockBar).doSomething(secondFooCaptor.capture());
// then do some assertions on secondFooCaptor.getValue()
Run Code Online (Sandbox Code Playgroud)
但是我得到了一个TooManyActualInvocations例外,因为Mockito认为doSomething应该只调用一次.
如何验证第二次调用的参数doSomething?
Mockito框架@Mock和之间有什么区别@InjectMocks?
我有一个void返回类型的方法.它也可以抛出一些异常,所以我想测试那些被抛出的异常.由于同样的原因,所有尝试都失败了:
Stubber类型中的(T)方法不适用于参数(void)
任何想法如何让方法抛出指定的异常?
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
Run Code Online (Sandbox Code Playgroud) 有没有办法,使用Mockito来模拟一个类中的某些方法,而不是其他方法?
例如,在这个(公认的设计)Stock类中我想模拟getPrice()和getQuantity()返回值(如下面的测试片段所示),但我希望getValue()执行在Stock中编码的乘法类
public class Stock {
private final double price;
private final int quantity;
Stock(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public double getValue() {
return getPrice() * getQuantity();
}
@Test
public void getValueTest() {
Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);
when(stock.getQuantity()).thenReturn(200);
double value = stock.getValue();
// Unfortunately the following assert fails, because the mock Stock getValue() method does not perform the …Run Code Online (Sandbox Code Playgroud) 我在接口上有一个方法:
string DoSomething(string whatever);
Run Code Online (Sandbox Code Playgroud)
我想用MOQ模拟这个,以便它返回传入的内容 - 类似于:
_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
.Returns( [the parameter that was passed] ) ;
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
在Java中创建模拟对象的最佳框架是什么?为什么?每个框架的优缺点是什么?
mocking ×10
java ×6
unit-testing ×6
mockito ×5
stub ×2
c# ×1
definition ×1
exception ×1
moq ×1
terminology ×1
testing ×1
void ×1