标签: spring-boot-test

spring boot - 应用程序启动两次..?

我是 Spring Boot 的新手,我的应用程序Servlet带有 eh-cache 模块。

@EnableCaching 
@SpringBootApplication 
@ServletComponentScan
public class Application extends SpringBootServletInitializer {

    private static final Logger log = LoggerFactory.getLogger(Application.class);
    public Application() {
        log.info("------------------------------");
        log.info("  Welcome to Application");
        log.info("------------------------------");
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这个,我试图启动应用程序,但它启动了两次..?

        12:11:36,020 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@291e5d10 - Registering current configuration as safe fallback point
    **2018-03-28_12:11:36.204 com.netapp.prj.Application - ------------------------------
    2018-03-28_12:11:36.226 com.ct.prj.Application -   Welcome to Application
    2018-03-28_12:11:36.226 com.ct.prj.Application - ------------------------------**

      .   ____          _            __ _ _
     /\\ / ___'_ …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-boot-test

4
推荐指数
2
解决办法
7816
查看次数

运行 SpringBootTest 时访问 H2 控制台

如果我正在运行测试,@SpringBootTest有没有办法访问 H2 控制台?我有一个访问 H2 数据库的测试(成功),但是如果我想自己检查数据库,我该怎么做?

我开始与运行测试webEnvironment=DEFINED_PORTHTTP://本地主机:8080 /响应HTTP,但没有什么的http://本地主机:8080 / H2控制台/仍以404响应。

我尝试通过向以下项添加值来显式打开控制台application.properties

spring.h2.console.enabled=true
spring.h2.console.path=/h2
Run Code Online (Sandbox Code Playgroud)

那似乎没有效果。仍然是 404/h2-console/h2

H2 控制台似乎是通过自动配置进入的,所以我使用 开启了自动配置报告-Ddebug,我可以看到尽管在 application.properties 中启用了启用标志,但它被视为关闭:

H2ConsoleAutoConfiguration: 
      Did not match:
          - @ConditionalOnProperty (spring.h2.console.enabled=true) did not find property 'enabled' (OnPropertyCondition)
      Matched:
         - @ConditionalOnClass found required class 'org.h2.server.web.WebServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
         - found WebApplicationContext (OnWebApplicationCondition)
Run Code Online (Sandbox Code Playgroud)

似乎某种机制application.properties在运行测试时覆盖了该值或忽略了该值。

Spring Boot Test 不启动控制台吗?有什么方法可以说服它这样做吗?

spring-boot spring-boot-test

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

每次测试后撤消@Sql

我有一些 junit 测试,我想用一些对测试实际有意义的数据预先填充数据库:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class MyTest {


@Sql("test_insert.sql") 
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}
Run Code Online (Sandbox Code Playgroud)

我注意到 junit 以相反的顺序执行测试,这意味着我的 testDelete 将首先执行。

测试插入似乎因“重复行约束”而失败,这是因为 test_delete.sql 脚本实际上添加了该行。

是否可以回滚@Sql 和测试本身所做的操作,以便一个测试不会影响其他测试?

spring spring-test spring-boot spring-boot-test

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

Spring Boot:自定义属性配置和测试

我正在使用带有默认application.yml属性文件的Spring Boot 2.0 。我想将它拆分为单独的属性文件,因为它变得很大。
此外,我想编写测试来检查属性的正确性:将出现在生产应用程序上下文(而不是测试上下文)中的值。

这是我的属性文件:src/main/resources/config/custom.yml

my-property:
  value: 'test'
Run Code Online (Sandbox Code Playgroud)

属性类:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Data
@Configuration
@ConfigurationProperties(prefix = "my-property")
@PropertySource("classpath:config/custom.yml")
public class MyProperty {

  private String value;
}
Run Code Online (Sandbox Code Playgroud)

测试:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyProperty.class)
@EnableConfigurationProperties
public class MyPropertyTest {

  @Autowired
  private MyProperty property;

  @Test
  public void test() {
    assertEquals("test", property.getValue());
  }

}
Run Code Online (Sandbox Code Playgroud)

但测试失败并出现错误:

java.lang.AssertionError: 
Expected :test
Actual   :null
Run Code Online (Sandbox Code Playgroud)

我还看到属性值是 …

java spring spring-boot spring-boot-test

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

使用 spring boot 测试抛出空指针异常

我是 Spring Boot 的新手,我正在尝试测试一个非常简单的类。但是当我运行testMe()下面的我得到下面的异常

java.lang.NullPointerException
    at MyTest.testMe(MyTest.java:25)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
Run Code Online (Sandbox Code Playgroud)

我的理解是,当加载上下文时,所有 bean 都被初始化,对象HelloWorld被创建并在MyTest调用中自动装配。但是helloWorld对象null在一条线上 helloWorld.printHelloWorld();

我需要帮助来了解缺少什么。

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = {AppConfigTest.class})
public class MyTest {

    @Mock
    @Autowired
    private Message myMessage;

    @Autowired
    private HelloWorld helloWorld;

    @Test
    public void testMe(){
       helloWorld.printHelloWorld();
    }
}


@Configuration
public class AppConfigTest {

   @Bean
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }

    @Bean
    public Message getMessage(){
        return new Message("Hello");
    }
}

public interface HelloWorld {
    void printHelloWorld();
} …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-boot-test

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

MockHttpServletRequestBuilder - 如何更改 HttpServletRequest 的 remoteHost 的 remoteAddress?

我正在尝试为集成测试(@SpringBootTest)创建模拟请求。

//given     
MockHttpServletRequestBuilder requestBuilder = get("/users/register/user1");
Run Code Online (Sandbox Code Playgroud)

我想检查的是这个请求的遥控器。在我的控制器中,我从HttpServletRequest获取此信息

HttpServletRequest request;
request.getRemoteHost();
request.getRemoteAddr();
Run Code Online (Sandbox Code Playgroud)

不幸的是,现在getRemoteHost()总是会返回localhost

我想在我的模拟请求中将其更改为其他内容,例如:

远程主机:localhost-->mockhostdomain

远程地址:127.0.0.1--> 10.32.120.7(任何不同)

我找不到合适的方法。甚至有可能吗?

java spring-mvc spring-boot mockmvc spring-boot-test

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

@SpringBootTest 与 @WebMvcTest & @DataJpaTest &service 单元测试,哪个最好?

我有一个 SpringBoot MVC 应用程序,我想用测试来覆盖它。

我有控制器、服务和存储库层。

通过测试覆盖应用程序的最佳实践是什么?

为什么人们使用@SpringBootTest它似乎可以通过@WebMvcTest@DataJpaTest和服务单元测试进行层测试?它更快,更精细,不是吗?

AFAIK 什么时候@SpringBootTest使用它被称为集成测试,所以这是否意味着它不应该经常出现?

我想每一块代码都应该被单元测试覆盖,集成覆盖是否相同?或者集成测试应该在舞台环境中工作而不是在测试环境中工作?

如果我创建一个@SpringBootTest但模拟其他层,是不是一样(在性能方面)?(假设我创建了多个@SpringBootTests 并模拟其他层)。

unit-testing spring-mvc spring-boot spring-boot-test

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

如何在 spring junit 测试中禁用日志记录(错误除外)?

我有一个/src/test/resources/application.properties简单的spring-boot项目:

spring.main.banner-mode=off
logging.level.root=ERROR
logging.level.org.springframework.*=ERROR
Run Code Online (Sandbox Code Playgroud)

问题:在测试运行期间,我仍然在控制台中看到以下输出:

12:15:33.323 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
12:15:33.373 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
12:15:33.515 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [ServletITest] from class [org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper]
12:15:33.568 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.slr.hellodocker.HelloServletITest], using SpringBootContextLoader
12:15:33.576 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [ServletITest]: class path resource [ServletITest-context.xml] does …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-boot-test

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

使用 MockMvc 进行 Spring Boot Aspectj 测试

我有一个带有 Aspectj 的 Spring 启动代码。这段代码是用基本的 MVC 架构编写的。然后我只是尝试用 MockMVC 测试它。但是当我尝试对其进行测试时,Aspectj 并没有中断。Aspectj 有没有特殊的配置?

控制器:

@GetMapping("user/{userId}/todo-list")
public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){
    ...handle it with service method.
}
Run Code Online (Sandbox Code Playgroud)

方面:

@Pointcut("execution(* *(.., @RequestUser (*), ..))")
void annotatedMethod()
{
}

@Before("annotatedMethod() && @annotation(requestUser)")
public void adviseAnnotatedMethods(JoinPoint joinPoint, RequestUser requestUser)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

测试:

@WebMvcTest(value = {Controller.class, Aspect.class})
@ActiveProfiles("test")
@ContextConfiguration(classes = {Controller.class, Aspect.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest
{
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private Controller controller;

    @MockBean
    private Service service;

    @Before
    public void …
Run Code Online (Sandbox Code Playgroud)

java aspectj spring-boot spring-boot-test

4
推荐指数
2
解决办法
885
查看次数

MockMVC 不是自动装配的,它是 null

我在将 MockMvc 注入我的测试类时遇到问题。我尝试了几个选项,但没有一个有效。

1个选项:和这里基本一样,手动创建MockMvc

@Autowire MockMvc - Spring Data Rest

2选项:

    package com.application.controller;
    
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class DishControllerTest {

    @Autowired
    public MockMvc mockMvc;


    @Test
    void getDishes() throws Exception {
        this.mockMvc.perform(
                get("/"))
                .andDo(print())
                .andExpect(status().isOk());
    }
Run Code Online (Sandbox Code Playgroud)
  1. 还尝试使用 @WebMvcTest 注释而不是 @AutoConfigureMockMvc 的第二个选项

MockMVC 一直为空。堆栈跟踪:

java.lang.Exception: No runnable methods

    at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
    at …
Run Code Online (Sandbox Code Playgroud)

java junit spring-boot mockmvc spring-boot-test

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