我有一个运行简单REST服务Spring Boot应用程序。我想测试一下这项服务。因为我喜欢Spock框架,所以我很愿意在这里使用它,但是我不能通过Spring配置的问题。
@RestController
public class RestHandler {
private @Autowired ExecutionService executionService;
public RestHandler(ExecutionService executionService) {
this.executionService = executionService;
}
@RequestMapping(value = "/toolbox/exec", method = POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String executeTool(@RequestBody Tool tool) {
executionService.execute(tool);
return "thanks";
}
}
@SpringBootApplication
public class ToolExecutor {
public static void main(String[] args) {
SpringApplication.run(ToolExecutor.class, args);
}
}
@SpringBootTest
class RestHandlerTest extends Specification {
def someService = Mock(ExecutionService)
def underTest = new RestHandler(someService);
def mockMvc = MockMvcBuilders.standaloneSetup(underTest).build()
@Shared
def client = new RESTClient("http://localhost:603/toolbox/exec")
def "ExecuteToolTest"() {
when: "If POST has valid JSON format"
Closure object = { "{\"name\":\"test\",\"parameters\":[\"abc\",\"def\"]}" }
def response = client.request(Method.POST, object);
then:
with(response){
data.text == "thanks"
status == 200
}
}
}
日志
15:22:07.601 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:22:07.605 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:22:07.605 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
15:22:07.855 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Looking for request mappings in application context: org.springframework.test.web.servlet.setup.StubWebApplicationContext@17f9d882
15:22:07.897 [main] DEBUG org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - 2 request handler methods found on class com.company.toolbox.components.executor.RestHandler: {public void com.company.toolbox.components.executor.RestHandler.isAlive()={[/toolbox/exec],methods=[GET]}, public java.lang.String com.company.toolbox.components.executor.RestHandler.executeTool(com.company.toolbox.commons.Tool)={[/toolbox/exec],methods=[POST],consumes=[application/json],produces=[text/plain]}}
15:22:07.900 [main] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/toolbox/exec],methods=[GET]}" onto public void com.company.toolbox.components.executor.RestHandler.isAlive()
15:22:07.907 [main] INFO org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/toolbox/exec],methods=[POST],consumes=[application/json],produces=[text/plain]}" onto public java.lang.String com.company.toolbox.components.executor.RestHandler.executeTool(com.company.toolbox.commons.Tool)
15:22:08.285 [main] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
15:22:08.286 [main] INFO org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.4.Final
15:22:08.307 [main] DEBUG org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver - Cannot find javax.persistence.Persistence on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.
15:22:08.317 [main] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
15:22:08.318 [main] DEBUG org.hibernate.validator.internal.engine.ConfigurationImpl - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy26
15:22:08.320 [main] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - Trying to load META-INF/validation.xml for XML based Validator configuration.
15:22:08.323 [main] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via TCCL
15:22:08.324 [main] DEBUG org.hibernate.validator.internal.xml.ResourceLoaderHelper - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
15:22:08.324 [main] DEBUG org.hibernate.validator.internal.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only.
15:22:08.386 [main] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@17f9d882
15:22:08.422 [main] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Looking for exception mappings: org.springframework.test.web.servlet.setup.StubWebApplicationContext@17f9d882
15:22:08.442 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Initializing servlet ''
15:22:08.452 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletConfigInitParams] PropertySource with lowest search precedence
15:22:08.452 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [servletContextInitParams] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
15:22:08.455 [main] DEBUG org.springframework.web.context.support.StandardServletEnvironment - Initialized StandardServletEnvironment with PropertySources [servletConfigInitParams,servletContextInitParams,systemProperties,systemEnvironment]
15:22:08.455 [main] INFO org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
15:22:08.455 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
15:22:08.457 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using LocaleResolver [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@267f474e]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using ThemeResolver [org.springframework.web.servlet.theme.FixedThemeResolver@7a7471ce]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using RequestToViewNameTranslator [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@28276e50]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Using FlashMapManager [org.springframework.web.servlet.support.SessionFlashMapManager@62e70ea3]
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Published WebApplicationContext of servlet '' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.]
15:22:08.458 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 3 ms
15:22:08.458 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Servlet '' configured successfully
15:22:08.476 [main] DEBUG groovyx.net.http.RESTClient - POST http://localhost:603/toolbox/exec
15:22:08.728 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {}->http://localhost:603
15:22:08.742 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:603
15:22:09.744 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connect to localhost:603 timed out. Connection will be retried using another IP address
15:22:09.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:603
15:22:10.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection@21362712 closed
15:22:10.745 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection@21362712 shut down
15:22:10.746 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@27eb3298
例外情况
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:120)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:476)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:441)
at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:373)
at com.xetra11.toolbox.components.executor.RestHandlerTest.ExecuteToolTest(RestHandlerTest.groovy:26)
Process finished with exit code -1
这就是你需要的
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RestHandlerTest extends Specification {
@Autowired
TestRestTemplate testRestTemplate
然后使用testRestTemplate代替Client。您还需要添加spock-spring依赖项。
我们实际上使用了JUnit和FakeSftpServerRule来测试我们定制的SFTP客户端。效果很好。 最后,我们希望摆脱junit,转而使用spock框架,因为我们试图迁移到groovy。 你们知道FakeSftpServerRule的等价物吗?或者,你们知道把junit规则“转换”成spock规则等价物的方法吗? 非常感谢。
问题内容: 有人可以帮我这个忙。我正在使用Jersey休息测试框架版本2.21(在Grizzly容器上)编写Rest资源的单元测试。 当我调试测试类时,看到myManager的模拟对象。但是,当调试进入“ MyResouce类”时,myManager对象将变为null并得到NullPointer异常。 尝试过其他人提供的解决方案,但是没有运气。请有人帮我。我将近三天就遇到这个问题。:( 我的资源类
因此,我正在进行我的第一个Spring Boot项目,我一直在进行测试。我查了很多例子,但似乎都不管用。 这是我的控制器的当前测试: 这是可行的,但在sonarqube上,我发现我的代码覆盖率为0%,而我似乎找不到一个测试,它的覆盖率甚至超过了零。有谁能给我一个关于如何为控制器编写一个好的单元测试的例子,然后我就可以根据您的例子自己解决这个问题。 这是我的控制器: 这是我的服务(以防您需要): 还
我无法使用安全性配置我的Spring Boot服务器的“自测”。这意味着我使用本教程创建了一个自签名证书。当我从浏览器打开https://localhost:8080时,没有问题,我有一个安全的加密连接。 但是,当我想要设置一个REST模板来调用https://localhost:8080时,我得到了这个错误: 测试类和项目:https://github.com/mpawel1993/family
英文原文:http://emberjs.com/guides/testing/testing-controllers/ 单元测试方案和计算属性与之前单元测试基础中说明的相同,因为Ember.Controller集成自Ember.Object。 针对控制器的单元测试使用ember-qunit框架的moduleFor来做使这一切变得非常简单。 测试控制器操作 下面给出一个PostsController
测试框架工具 Karma Intern NightWatch.js