环境:我有一个基于spring boot的微服务架构应用程序,包括多个基础结构服务和资源服务(包含业务逻辑).授权和身份验证由oAuth2-Service处理,管理用户实体并为客户端创建JWT令牌.
为了完整地测试单个微服务应用程序,我尝试使用testNG,spring.boot.test,org.springframework.security.test构建测试...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false", "spring.profiles.active=test"})
@AutoConfigureMockMvc
@Test
public class ArtistControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private MockMvc mvc;
@BeforeClass
@Transactional
public void setUp() {
// nothing to do
}
@AfterClass
@Transactional
public void tearDown() {
// nothing to do here
}
@Test
@WithMockUser(authorities = {"READ", "WRITE"})
public void getAllTest() throws Exception {
// EXPECT HTTP STATUS 200
// BUT GET 401
this.mvc.perform(get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
}
Run Code Online (Sandbox Code Playgroud)
安全性(资源服务器)配置如下
@Configuration …Run Code Online (Sandbox Code Playgroud) 我正在使用一个安静的URL来启动长时间运行的后端进程(通常是在cron时间表上,但我们希望能够手动启动它).
下面的代码有效,我在手动测试时会在浏览器中看到结果.
@ResponseBody
@RequestMapping(value = "/trigger/{jobName}", method = RequestMethod.GET)
public Callable<TriggerResult> triggerJob(@PathVariable final String jobName) {
return new Callable<TriggerResult>() {
@Override
public TriggerResult call() throws Exception {
// Code goes here to locate relevant job and kick it off, waiting for result
String message = <result from my job>;
return new TriggerResult(SUCCESS, message);
}
};
}
Run Code Online (Sandbox Code Playgroud)
当我在没有Callable使用下面的代码的情况下进行测试时,一切正常(我更改了预期的错误消息以简化发布).
mockMvc.perform(get("/trigger/job/xyz"))
.andExpect(status().isOk())
.andDo(print())
.andExpect(jsonPath("status").value("SUCCESS"))
.andExpect(jsonPath("message").value("A meaningful message appears"));
Run Code Online (Sandbox Code Playgroud)
当我添加它Callable但它不起作用.我也在下面试过,但它没有用.其他人有成功吗?
mockMvc.perform(get("/trigger/job/xyz"))
.andExpect(status().isOk())
.andDo(print())
.andExpect(request().asyncResult(jsonPath("status").value("SUCCESS")))
.andExpect(request().asyncResult(jsonPath("message").value("A meaningful message appears")));
Run Code Online (Sandbox Code Playgroud)
以下是我的print()中的相关部分.看起来mockMvc在这种情况下无法正确解开Json(即使它在我的浏览器中有效)?当我这样做而没有Callable …
在Spring 3.2.5→4.0.0版本更新后尝试编译源时,我有奇怪的行为.
错误的代码片段ApplicationControllerTest.java(它相当于文档中的代码):
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
...
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
Run Code Online (Sandbox Code Playgroud)
错误:
COMPILATION ERROR :
/C:/Development/.../war/src/test/java/org/.../web/controller/ApplicationControllerTest.java:[59,61] C:\Development\...\war\src\test\java\org\...\web\controller\ApplicationControllerTest.java:59: incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) B
found : <B>org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder<B>
required: java.lang.Object
如果人们查看MockMvcBuilders来源,可以看出差异:
Spring 4.0.0:
public static <B extends DefaultMockMvcBuilder<B>> DefaultMockMvcBuilder<B> webAppContextSetup(WebApplicationContext context) {
return new DefaultMockMvcBuilder<B>(context);
}
Run Code Online (Sandbox Code Playgroud)
Spring 3.2.5:
public static …Run Code Online (Sandbox Code Playgroud) 我想知道如何为我的测试验证用户身份?现在,我将编写的所有测试都将失败,因为端点需要授权.
测试代码:
@RunWith(SpringRunner.class)
@WebMvcTest(value = PostController.class)
public class PostControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private PostService postService;
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("posts"));
}
}
Run Code Online (Sandbox Code Playgroud)
我找到的一个解决方案是通过在@WebMvcTest中将secure设置为false来禁用它.但这不是我想要做的.
有任何想法吗?
spring spring-mvc spring-security spring-test-mvc spring-boot
我正在测试我的MVC服务,spring-test-mvc我使用了类似的东西:
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("<my-url>")).andExpect(content().bytes(expectedBytes)).andExpect(content().type("image/png"))
.andExpect(header().string("cache-control", "max-age=3600"));
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.
现在我将缓存图像更改为在特定范围内随机.例如,而不是3600它3500-3700.我试图找出如何获取标头值并对其进行一些测试而不是使用此模式andExpect.
我有一个简单的Spring测试
@Test
public void getAllUsers_AsPublic() throws Exception {
doGet("/api/users").andExpect(status().isForbidden());
}
public ResultActions doGet(String url) throws Exception {
return mockMvc.perform(get(url).header(header[0],header[1])).andDo(print());
}
Run Code Online (Sandbox Code Playgroud)
我想验证响应正文是否为空.例如做类似的事情.andExpect(content().isEmpty())
我在Spring MVC中有一个带有可选路径变量的方法.我试图在没有提供可选路径变量的情况下测试它.
来自Controller的片段,用于调用的资源URI-
@RequestMapping(value = "/some/uri/{foo}/{bar}", method = RequestMethod.PUT)
public <T> ResponseEntity<T> someMethod(@PathVariable("foo") String foo, @PathVariable(value = "bar", required = false) String bar) {
LOGGER.info("foo: {}, bar: {}", foo, bar);
}
Run Code Online (Sandbox Code Playgroud)
我使用MockMvc测试的片段 -
//inject context
@Autowired
private WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
@Before
public void setup() {
//build mockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void someMethodTest() throws Exception {
//works as expected
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", "bar"))
.andExpect(status().isOk()); //works
//following doesn't work
//pass null for optional
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", null))
.andExpect(status().isOk()); //throws …Run Code Online (Sandbox Code Playgroud) 我已多次阅读文档(http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/testing.html#spring-mvc-test-framework),我可以确认WebApplicationContext在使用@WebApplicationContext注释时注入的上下文是否实际上是在查看web.xml.
换句话说,我想测试我的web.xml配置.特别是过滤器和servlet路径.但是当我配置我的测试时,它会忽略web.xml.(例如,我get在这样的URL上尝试请求/myServletPath/foo,但它失败了404.)
我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({
"classpath*:WEB-INF/config/application-context.xml",
"classpath*:WEB-INF/oms-servlet.xml",
"classpath*:persistence-context.xml"
})
public class OrderSummaryControllerIntegrationTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void testFindOrderSummariesExpectsSuccess() throws Exception {
mockMvc.perform(get("/oms/orders?user=1234&catalog=bcs"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}
Run Code Online (Sandbox Code Playgroud)
还有我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>OMS REST Services</display-name>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<filter>
<filter-name>webappMetricsFilter</filter-name>
<filter-class>com.yammer.metrics.web.DefaultWebappMetricsFilter</filter-class>
</filter> …Run Code Online (Sandbox Code Playgroud) spring integration-testing web.xml spring-mvc spring-test-mvc
我有一个使用 JPA 存储库(CrudRepository接口)的 Spring 应用程序。当我尝试使用新的 Spring 测试语法测试我的控制器时@WebMvcTest(MyController.class),它失败了,因为它试图实例化我的一个使用 JPA 存储库的服务类,有没有人知道如何解决这个问题?该应用程序在我运行时有效。
这是错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.myapp.service.UserServiceImpl required a bean of type 'com.myapp.repository.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.myapp.repository.UserRepository' in your configuration.
Run Code Online (Sandbox Code Playgroud) spring spring-mvc spring-data-jpa spring-test-mvc spring-boot
我想@EnableAsync在运行集成测试时禁用.
我试图覆盖配置文件,该文件使用@EnableAsync我的测试包中具有相同名称的类进行注释,但它不起作用.
在本主题中:是否可以在集成测试期间禁用Spring的@Async?
我看到了:
您可以...创建测试配置或使用SyncTaskExecutor简单地覆盖任务执行程序
但我不明白该怎么做.
有什么建议?谢谢
spring-test-mvc ×10
spring ×7
spring-mvc ×7
java ×4
spring-boot ×4
spring-test ×3
json ×1
spring-4 ×1
web.xml ×1