我正在使用 Spock fw 和 Mockito。我有一个名为“HostController”的控制器和一个名为“HostService”的服务。
'HostController' 的方法称为 as host(Long id),'HostService' 的方法称为 as findOne(Long id)。
我想测试HostController#host(Long id),所以我想到了存根findOne(Long id)方法。
以下是测试代码:
class MockTest extends Specification {
@Mock
private HostService mockedService;
@InjectMocks
private HostController controller;
def setup() {
MockitoAnnotations.initMocks(this);
}
def "mock test"() {
given:
def host = new Host(id: 1, ipAddress: "127.0.0.1", hostName: "host1")
mockedService.findOne(_) >> host
when:
Map<String, Object> result = controller.host(1)
then:
result.get("host") != null
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的测试中,controller.host(1)返回Map<String, Object>类型并且它的键名为host. …