[英]Using Spock/Groovy to test a Java method that extends HashMap - how to mock HashMap get method?
在我們的代碼庫中,我們使用特定的 class map 存儲授權請求的結果,包括是否有人具有進入的授權。
目前正在編寫一些包含此內容的單元測試(我很少練習),我們的代碼的修改版本供您查看:
public class TestResultMap extends HashMap<String, TestResult> {
private static final long serial = -1234567890L;
public boolean isAuthorized(String resource) {
TestResult result = get(resource);
if (result == null) {
throw new RunExcept("Authorization not calculated");
}
return result.isAuthorized();
}
}
在我制作的 groovy 文件中測試 isAuthorized() 時,我注意到無論我如何安排它,我都無法將 TestResult result = get(resource) 實例化為 null 以外的任何內容。 isAuthorized() 調用另一個包含可能性的 class 中的枚舉方法,否則只返回 boolean。
不過,這是切題的。 有沒有一種有效的方法來模擬這個或強制 get(resource) 到 output 不是 null 的東西? 或者,我可以直接將結果設置為特定值嗎?
謝謝你的幫助。 整個過程令人難以置信的新事物和文檔一直很棘手。
我給你看
TestResult.isAuthorized
的結果始終返回true
或false
,TestResultMap
實例上使用間諜,以便使用 class 行為正常的 rest 存根get(_)
的結果(部分模擬),正在測試的課程:
package de.scrum_master.stackoverflow.q70149644;
public class TestResult {
private String result;
public TestResult(String result) {
this.result = result;
}
public boolean isAuthorized() {
return !result.toLowerCase().matches(".*(forbidden|blocked|unauthorized|denied).*");
}
@Override
public String toString() {
return "TestResult(result='" + result + "')";
}
}
package de.scrum_master.stackoverflow.q70149644;
import java.util.HashMap;
public class TestResultMap extends HashMap<String, TestResult> {
private static final long serial = -1234567890L;
public boolean isAuthorized(String resource) {
TestResult result = get(resource);
if (result == null) {
throw new RuntimeException("Authorization not calculated");
}
return result.isAuthorized();
}
}
斯波克規格:
package de.scrum_master.stackoverflow.q70149644
import spock.lang.Specification
class TestResultMapTest extends Specification {
def "resource is authorized"() {
given:
TestResultMap map = new TestResultMap()
TestResult testResult = Stub() {
isAuthorized() >> true
}
map.put("resource", testResult)
expect:
map.isAuthorized("resource")
}
def "resource is unauthorized"() {
given:
TestResultMap map = new TestResultMap()
TestResult testResult = Stub() {
isAuthorized() >> false
}
map.put("resource", testResult)
expect:
!map.isAuthorized("resource")
}
def "resource not found"() {
given:
TestResultMap map = Spy() {
get(_) >> null
}
when:
map.isAuthorized("resource")
then:
def rte = thrown RuntimeException
rte.message == "Authorization not calculated"
}
def "test without mocks"() {
given:
TestResultMap map = new TestResultMap()
map.put("OK", new TestResult("Hello world"))
map.put("not OK", new TestResult("Access denied"))
expect:
map.isAuthorized("OK")
!map.isAuthorized("not OK")
when:
map.isAuthorized("foo")
then:
def rte = thrown RuntimeException
rte.message == "Authorization not calculated"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.