我在使用@MockBean注释时遇到问题.文档说MockBean可以替换上下文中的bean,但是我在单元测试中得到NoUniqueBeanDefinitionException.我看不出如何使用注释.如果我可以模拟repo,那么很明显会有多个bean定义.
我正在按照此处的示例进行操作:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
我有一个mongo存储库:
public interface MyMongoRepository extends MongoRepository<MyDTO, String>
{
MyDTO findById(String id);
}
Run Code Online (Sandbox Code Playgroud)
泽西岛资源:
@Component
@Path("/createMatch")
public class Create
{
@Context
UriInfo uriInfo;
@Autowired
private MyMongoRepository repository;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createMatch(@Context HttpServletResponse response)
{
MyDTO match = new MyDTO();
match = repository.save(match);
URI matchUri = uriInfo.getBaseUriBuilder().path(String.format("/%s/details", match.getId())).build();
return Response.created(matchUri)
.entity(new MyResponseEntity(Response.Status.CREATED, match, "Match created: " + matchUri))
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个JUnit测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMocks {
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private MyMongoRepository mockRepo; …Run Code Online (Sandbox Code Playgroud) 我不明白为什么下面的代码不能编译:
private ResponseEntity<JSendResponse> buildResponse(RequestModel requestModel,
RequestModelParamConverter paramConverter,
Supplier<String> xsdSupplier,
Supplier<String> xmlTemplateSupplier) {
return Optional.ofNullable(new RequestErrorHandler<>().validate(validator, requestModel))
.map(validationErrors -> new ResponseEntity<>(validationErrors, HttpStatus.BAD_REQUEST))
.orElse(this.buildResponseForValidRequest(requestModel, paramConverter, xsdSupplier, xmlTemplateSupplier));
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
"可选"中的orElse(org.springframework.http.ResponseEntity <com.company.util.response.JSendFailResponse>)无法应用于(org.springframework.http.ResponseEntity <com.company.util.response.JSendResponse>)
虽然这段代码(我认为逻辑上是相同的代码)确实编译:
private ResponseEntity<JSendResponse> buildResponse(RequestModel requestModel,
RequestModelParamConverter paramConverter,
Supplier<String> xsdSupplier,
Supplier<String> xmlTemplateSupplier) {
JSendResponse validationErrors = new RequestErrorHandler<>().validate(validator, requestModel);
if(validationErrors == null) {
return this.buildResponseForValidRequest(requestModel, paramConverter, xsdSupplier, xmlTemplateSupplier);
}
else
{
return new ResponseEntity<>(validationErrors, HttpStatus.BAD_REQUEST);
}
}
Run Code Online (Sandbox Code Playgroud)
问题似乎是如果验证失败,RequestErrorHandler <>().validate方法返回一个名为JSendFailResponse的类.JSendFailResponse是JSendResponse的子类,它最终返回.似乎lambda代码无法理解JSendFailResponse是一个JSendResponse.
如果我将validationErrors转换为map lambda中的JSendResponse,我可以编译它,但是我丢失了JSendFailResponse上的一些字段.
编辑:此代码也无法编译:
private ResponseEntity<? extends JSendResponse> buildResponse(RequestModel requestModel,
RequestModelParamConverter paramConverter,
Supplier<String> …Run Code Online (Sandbox Code Playgroud) 阅读本文档: https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_client.html
我可以看到如何配置 Spring-Cloud-Config 服务器来注册 Eureka。我没有看到如何配置 Spring-Cloud-Config 客户端应用程序以通过 Eureka 发现 Spring-Cloud-Config 服务器。
可以安全地假设,如果我有一个 Spring-Boot 应用程序需要联系 Spring-Cloud-Config 服务器来检索属性,那么只需使用 @DiscoveryClient 注释该应用程序就足以自动定位 Eureka 服务器,发现 Spring 的位置-云配置和检索属性?看来我至少需要使用 Spring-Cloud-Config 服务器的服务 ID 配置客户端。但我不知道如何做到这一点。
我第一次使用 Spring Boot 应用程序时,执行器没有受到保护,因此很容易通过 /actuator/shutdown 端点远程关闭。最近,我使用 Spring security 保护了我的执行器,并且它起作用了。现在我需要提供 http 基本凭据来访问端点,但现在对 /actuator/shutdown 端点的curl 调用失败并出现禁止错误。我一定是某个地方配置不正确。
我的卷曲命令:
curl -XPOST -u 执行器:密码http://主机:端口/执行器/shutdown -k
我可以调用其他端点,似乎只有关闭端点被禁止。
我的配置:
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.info.git.mode=full
management.endpoint.shutdown.enabled=true
management.server.port=8081
spring.security.user.name=actuator
spring.security.user.roles=ACTUATOR
spring.security.user.password=password
Run Code Online (Sandbox Code Playgroud)
编辑:
@Configuration
public static class ActuatorWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
.anyRequest().hasRole("ACTUATOR")
.and()
.httpBasic();
}
}
Run Code Online (Sandbox Code Playgroud) 我的考试不及格,应该通过。该服务运行正常,但是JerseyTest JUnit测试失败,状态为400。
当我针对已部署的服务尝试使用此URL时,使用Postman或浏览器:
http://localhost:8080/myService/123?appId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)
我得到正确的结果,状态为200,并在日志中看到以下内容:
INFO: 4 * Server has received a request on thread http-nio-8080-exec-5
4 > GET http://localhost:8080/myService/123?appId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)
注意?在URL中,这是正确的。
但是,当我在JeryseyTest扩展的Junit类中尝试此单元测试时:
@Test
public void getWithCorrectUrlExecutesWithoutError()
{
String x = target("myService/123?appId=local&userId=jcn").request().get(String.class);
}
Run Code Online (Sandbox Code Playgroud)
它失败并显示状态400,我在日志中看到了这一点:
INFO: 1 * Server has received a request on thread grizzly-http-server-0
1 > GET http://localhost:9998/myService/123%3FappId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)
注意吗?已被%3F取代。
我不明白发生了什么。如果在浏览器中尝试“%3F” URL,则单元测试中会看到相同的400错误。因此,我可以肯定地确定url的编码是问题所在。
这是我的Jersey资源,部分列出,因为它很长,但是我很确定这是相关的部分:
@Component
@Path("/myService")
public class MyResource
{
@Autowired
SomeDao someDao;
@NotBlank
@QueryParam("appId")
private String appId;
@NotBlank
@QueryParam("userId")
private String userId;
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Status getStatus(@NotBlank @PathParam("id") String id) …Run Code Online (Sandbox Code Playgroud) java ×3
spring-boot ×2
curl ×1
java-8 ×1
jersey ×1
junit ×1
mockito ×1
mongodb ×1
spring-data ×1
unit-testing ×1