标签: spring-test

使用自动装配的 MockHttpServletRequest 进行的多次测试不起作用?

@Autowired MockHttpServletRequest在一些 Spring 测试中使用了 。TestNG用作测试框架。如果我在课堂上只有一种测试方法,那么效果很好。但是,如果有多个测试方法,则只有第一个运行测试使用我的 MockHttpServletRequest。让我用一个例子来说明:

@WebAppConfiguration
@ContextConfiguration({"classpath:applicationContext.xml"})
public class FooTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private MockHttpServletRequest servletRequest;

    @Test
    public void test1() {
        assertEquals(((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(), servletRequest);
    }

    @Test
    public void test2() {
        assertEquals(((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(), servletRequest);
    }

}
Run Code Online (Sandbox Code Playgroud)

在此示例中,test1()通过了,但test2()失败了!如果单独运行测试方法,它们都会通过。如果一起运行,为什么一项测试会失败?

我尝试深入研究代码,在测试方法运行后似乎会重置请求属性,但我没有找到将其关闭的方法。我的 Spring 版本是 3.2.8.RELEASE。

testng spring spring-test

2
推荐指数
1
解决办法
1507
查看次数

验证接受对象数组的方法调用

我想验证是否调用了以下方法

MessageSourceAccessor.getMessage(String code, Object[] args, Locale locale)
Run Code Online (Sandbox Code Playgroud)

数组的第 10 个成员args等于“CHF”,我不想检查该数组的其他成员。

到目前为止,我尝试了以下构造:

Object [] obj = new Object[] {anyObject(),
        anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), "CHF", anyObject(), anyObject()};

verify(msa, times(1))
        .getMessage(eq("invoice.emailBody.1"), aryEq(obj), any(Locale.class));
Run Code Online (Sandbox Code Playgroud)

不幸的是,mockito 抱怨我在这种情况下不能使用 anyObject() 。另一方面,如果我不使用它,我必须为所有数组成员提供值,这不是我想要的。
也许以前有人遇到过这个问题?如果是这样,我将不胜感激任何帮助

谢谢

java junit spring-test mockito

2
推荐指数
1
解决办法
5091
查看次数

WebTestClient 检查 jsonPath 是否包含子字符串

在 MockMvc 中,可以断言 jsonPath 包含 substing

.andExpect(jsonPath("$.error.message")
.value(containsString("message")))
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一个很好的方法可以为 WebTestClient 做同样的事情,语法有点不同

webClient.post().uri("/test")
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(MyRequest), MyRequest.class)
                .exchange()
                .expectStatus().isBadRequest()
                .expectBody()
                .jsonPath("$.message").isEqualTo("message")
Run Code Online (Sandbox Code Playgroud)

但我发现只有与它相关的 isEqualTo 方法。

它可以通过从 WebTestClient.BodyContentSpec 中提取 getBodyAsString() 来完成,但它看起来不太好。

java spring-test reactive

2
推荐指数
3
解决办法
8596
查看次数

为什么@WebMvcTest 中的 POST 请求返回 403 和 permitAll()

我正在测试具有 POST 映射的控制器。这是摘录:

@RequestMapping(path = "/bookForm", method = POST)
public String saveBook(@Valid @ModelAttribute(name = "book") BookCommand bookCommand,
                       BindingResult bindingResult) {
        // blah blah

        return "redirect:/books";
    }
Run Code Online (Sandbox Code Playgroud)

我在玩 Spring 安全,所以我写了一个测试,我希望我的一些GET映射会被未经授权的用户拒绝,但是对于这个 POST 方法,我想允许所有。

这是一个测试配置类:

@Configuration
public class SecurityTestConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/books/**").authenticated()
                .antMatchers(HttpMethod.POST, "/bookForm").permitAll()
                .and()
                .httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,mockMvc对于 POST 调用仍然返回 4xx。这是为什么?

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
@Import(SecurityTestConfig.class)
public class BookControllerIT {

    @Autowired
    private MockMvc mockMvc;

    // ... mocks ect …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-security spring-test spring-boot

2
推荐指数
1
解决办法
2159
查看次数

Assertj 3.16.1 中是否弃用了方法“hasOnlyElementsOfType”

我有这段代码在更新到 Assertj 3.16.1 后不再有效

Throwable thrown = catchThrowable(() -> myObject.methodThrowsException());
assertThat(thrown).isInstanceOf(MyCustomException.class).extracting("fault").hasOnlyElementsOfType(CustomException.class).extracting("code").containsExactly("AnotherCustomException");
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

java:cannot find symbol
symbol: method hasOnlyElementsOfType(java.lang.Class<CustomException.class>)
location: class org.assertj.core.api.AbstractObjectAssert<capture#1 of?, capture#2 of ?>
Run Code Online (Sandbox Code Playgroud)

它要么已被弃用,要么现在以不同的方式实施。我已经浏览了文档并搜索了近两天,看看是否有任何关于如何使用它的信息,而不是以前如何使用它来实现轻松转换,但还没有找到任何东西。当我用它containsOnlyOnceElementsOf代替给出问题的那个时,我实际上得到了一个类似的错误。这些方法是否有其他替代方法可以实现相同的目的?

任何帮助将不胜感激!!!

java spring-test java-8 assertj junit5

2
推荐指数
1
解决办法
525
查看次数

为什么 RANDOM_PORT 不可分配?

我用硬编码的 url 进行了一些测试baseUrl = "http://localhost:8080/api/v1/"。当我尝试将其交换为 时baseUrl = "http://localhost:" + port + "/api/v1/",我得到

Caused by: java.net.NoRouteToHostException: 
Can't assign requested address (Address not available).
Run Code Online (Sandbox Code Playgroud)

这里有什么问题呢?

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class UrlShorteningControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    private int port;

    private String baseUrl = "http://localhost:" + port + "/api/v1/";
    // private String baseUrl = "http://localhost:8080/api/v1/";  // THIS WORKS FINE

        @Test
        void findAndRedirectHappyPath() throws URISyntaxException {
        final String dishpodUrl = baseUrl + "dishpods";

        URI uri = new URI(dishpodUrl);

        ResponseEntity<String> result …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-test

2
推荐指数
1
解决办法
737
查看次数

Spring Security 6 中用于自动化测试的标头配置

我使用以下配置代码使用 Spring Security 进行自动化测试:

    @TestConfiguration
    public static class SecurityConfiguration {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http)
                throws Exception {
            http.headers().xssProtection().and()
                    .contentSecurityPolicy("default-src 'self'");
            return http.build();
        }
    }
Run Code Online (Sandbox Code Playgroud)

最近,我收到几个警告,因为这些方法被标记为已弃用:

The method xssProtection() from the type HeadersConfigurer<HttpSecurity> has been deprecated since version 6.1 and marked for removal
The method headers() from the type HttpSecurity has been deprecated since version 6.1 and marked for removal
The method contentSecurityPolicy(String) from the type HeadersConfigurer<HttpSecurity> has been deprecated since version 6.1 and marked for removal
The method and() …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-test http-headers

2
推荐指数
1
解决办法
3985
查看次数

JUnit:设置测试类的事务边界

我想在启动任何测试方法之前启动数据库事务,并在运行所有测试结束时回滚所有事务。

怎么办?我应该使用什么注释?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/testApplicationContext.xml"})
public class MyTests{

   public void setUp(){
    //Insert temporary data to Database
   }

   @Test
   public void testOne(){
     //Do some DB transactions
   }

   @Test void testTwo(){
     //Do some more DB transactions
   }

   public void tearDown(){
   //Need to rollback all transactions
   }


}
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-test junit4

1
推荐指数
1
解决办法
1万
查看次数

如何为所有测试仅一次初始化Spring applicationContext

我有一组基于Spring的测试。

为了快速执行测试,我想确保Spring上下文仅初始化一次,然后所有测试都应针对该上下文运行,然后将其关闭。

我已经尝试了以下方法:

  1. 使用@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(MyAnnotatedConfig.class)初始化spring上下文
  2. @RunWith(SpringJUnit4ClassRunner.class)@TestExecutionListeners({MyTestExecutionListener.class})与手写测试执行侦听器一起使用,该侦听器将初始化spring上下文并将其注入到具体的测试类中
  3. @BeforeClass在基类和静态字段中使用侦听器来存储spring上下文,以及@AfterClass用于关闭的

使用这三种方法,spring上下文似乎不止一次被初始化,这需要很多时间。看起来JUnit在运行测试时会卸载类,因此有时会丢失静态字段的内容。

有没有办法确保spring上下文仅初始化一次?

java spring spring-test junit4

1
推荐指数
1
解决办法
6591
查看次数

SpringRunner无法检测到配置

我有一个弹簧启动应用程序,正在尝试为其创建单元测试用例。下面是我要运行的代码,我没有任何配置文件(仅使用注释),因此加载所有配置的主类是ElastSearchBootApplicationclass。由于某种原因,我看到以下错误。

@ComponentScan(basePackages = "com.somename")
@SpringBootApplication
@EnableScheduling
public class ElastSearchBootApplication {

    private static final Logger LOG = LoggerFactory.getLogger(ElastSearchBootApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ElastSearchBootApplication.class, args);
    }

    @Autowired
    private ElastSearchLogLevel logsSearch;

    @Scheduled(fixedRate = 120000)
public void scheduledSearchLogs() {
        ...
Run Code Online (Sandbox Code Playgroud)

测试类别:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ElastSearchBootApplication.class)
public class LogSearchTest {

    @Mock
    private RestHighLevelClient client;
    @Mock
      private ExecutorService ALERT_POOL;

    @Before
    public void setUp() throws Exception {
          client = mock(RestHighLevelClient.class);
        ALERT_POOL = mock(ExecutorService.class);

        try {
            when(client.search(anyObject())).thenReturn(getResponse());
        } catch (Exception e) {
            // I …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-boot

1
推荐指数
1
解决办法
4845
查看次数