我正在嘗試使用阻塞變數來驗證協作者的方法失敗后的異步互動。這是我得到的:
public class ServiceAImpl {
private final ServiceB serviceB;
private final ServiceC serviceC;
@Override
public void createAccount(String userId) {
try {
serviceB.createUserAccount(userId);
} catch (Exception e) {
asyncSaveCreationError(e);
throw e;
}
}
private void asyncSaveCreationError(Exception e) {
runAsync(() -> saveCreationError(e));
}
private void saveCreationError(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
serviceC.save(pw.toString());
}
}
class ServiceAImplTest extends Specification {
def serviceB = Mock(ServiceB)
def serviceC = Mock(ServiceC)
@Subject
def subject = new ServiceAImpl(serviceB, serviceC)
def "createAccount - should throw Exception and save error"() {
given:
def result = new BlockingVariable<Boolean>(10)
when:
subject.createAccount("userId")
then:
1 * serviceB.createUserAccount(_) >> { throw new Exception() }
thrown(Exception)
1 * serviceC.save(_) >> { result.set(true) }
result.get()
0 * _
}
}
拋出例外,但從未設定阻塞變數,因此我收到以下錯誤:
BlockingVariable.get() timed out after 10.00 seconds
at spock.util.concurrent.BlockingVariable.get(BlockingVariable.java:113)*
我嘗試使用普通的 Thread.sleep 但總是失敗 serviceC.save
uj5u.com熱心網友回復:
破壞你代碼的事情是模擬互動是每個then塊中首先評估的東西,即使你首先列出其他東西。因此,為了使其作業,您需要使用第二個then塊,如檔案中的章節呼叫順序中所述。由于首先評估模擬,因此執行甚至不會達到result.get()等待足夠長的時間,以便可以觸發保存互動。
這應該可以解決您的問題:
class ServiceAImplTest extends Specification {
ServiceB serviceB = Mock()
ServiceC serviceC = Mock()
@Subject
def subject = new ServiceAImpl(serviceB, serviceC)
def "createAccount - should throw Exception and save error"() {
given:
def result = new BlockingVariable<Boolean>(10.0)
when:
subject.createAccount("userId")
then: 'first catch the exception and wait for the result'
thrown(Exception)
result.get()
then: 'verify mock interactions'
1 * serviceB.createUserAccount(_) >> { throw new Exception() }
1 * serviceC.save(_) >> { result.set(true) }
0 * _
}
}
您可以在Groovy Web 控制臺上測驗 MCVE
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369155.html
上一篇:異步加載串列時影片中的錯誤
