如何用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)
系统不会通过模拟触发.=(我想显示上面提到的系统状态.并根据它们做出断言.
当存在空格时,我收到以下错误:
Stubber类型中的(T)方法不适用于参数(void)
这是我的示例代码:
doNothing().when(mockRegistrationPeristImpl.create(any(Registration.class)));
public void create(final T record) throws DataAccessException {
try {
entityManager.persist(record);
entityManager.flush();
} catch (PersistenceException ex) {}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
我正在使用Guzzle 5.3,并想测试我的客户端抛出一个TimeOutException.
然后,我怎么能模拟Guzzle客户端抛出一个GuzzleHttp\Exception\ConnectException?
要测试的代码.
public function request($namedRoute, $data = [])
{
try {
/** @noinspection PhpVoidFunctionResultUsedInspection */
/** @var \GuzzleHttp\Message\ResponseInterface $response */
$response = $this->httpClient->post($path, ['body' => $requestData]);
} catch (ConnectException $e) {
throw new \Vendor\Client\TimeOutException();
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
正确的问题是:如何使用Guzzle 5抛出异常?或者,如何用Guzzle 5测试一个挡块?
我有一个process返回 void 的方法,也可能引发异常。我想验证其他方法run在调用时的行为方式process以及发生异常时的处理方式。
我尝试使用doThrow(),但它告诉我“检查的异常对此方法无效!”。然后我尝试使用thenThrow()但它需要一个非空函数。
代码:
public void run() {
for (var billet : getBillets()) {
try {
process(billet);
billet.status = "processed";
} catch (Exception e) {
billet.status = "error";
}
billet.update();
}
}
public void process(Billet billet) throws Exception {
var data = parse(billet.data); // may throw an exception
var meta = data.get("meta"); // may throw an exception
// ... more parsing ...
new Product(meta).save();
new Item(meta).save();
// ... more …Run Code Online (Sandbox Code Playgroud) 在School课堂上,我有一个start()调用另一个函数的函数doTask():
pubic class School {
public void start() {
try {
doTask();
} catch(RuntimeException e) {
handleException();
}
}
private void doTask() {
//Code which might throw RuntimeException
}
}
Run Code Online (Sandbox Code Playgroud)
我想单元测试start()有RuntimeException:
@Test
public void testStartWithException() {
// How can I mock/stub mySchool.start() to throw RuntimeException?
mySchool.start();
}
Run Code Online (Sandbox Code Playgroud)
我的实现代码抛出 并不容易RuntimeException,如何让测试代码模拟 RuntimeException 并抛出它?
(除了纯 JUnit,我正在考虑使用Mockito,但不确定如何抛出 RuntimeException)