标签: spring-boot-test

如何从SpringBootTest调试Spring Boot应用程序

我是Spring Boot的新手,我真的很喜欢它,尤其是在消除样板代码时。我创建了一个测试类来测试我的@RestController:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = NewBusinessRevitalizationApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"management.port=0"})
public class NBRControllerTest extends TestCase {

@LocalServerPort
private int port;

@Value("${local.management.port}")
private int mgt;

@Autowired
private TestRestTemplate testRestTemplate;

@Test
public void getApplicationByAgencyIdAndStatusTest() {
    String uri = "http://localhost:" + this.port + "/nbr-services/applications/{status}?agencyIds=123456,56765,678576";
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("status", "SAVED");
    ResponseEntity<String> response = testRestTemplate.getForEntity(uri, String.class, vars);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
}
Run Code Online (Sandbox Code Playgroud)

如果以调试模式运行它,则只能调试Test类,而不能调试@RestController类:

@RestController
@RequestMapping("/nbr-services")
public class NBRController {

@Autowired
private NBRServices nbrServices;

private static Logger logger = LoggerFactory.getLogger(NBRController.class);

@RequestMapping(value …
Run Code Online (Sandbox Code Playgroud)

debugging spring-boot spring-boot-test

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

带有 MockMvcBuilders 独立设置的 SpringBootTest 尽管设置了但没有加载我的 ControllerAdvice

我正在创建这样的控制器和控制器建议:

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {

    private MockMvc mockMvc;

    @Mock
    private MyService myService;

    @Autowired
    @InjectMocks
    private MyController myController;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);

        //Build the controller mock handler
        mockMvc = MockMvcBuilders
            .standaloneSetup(MyController.class)
            .setControllerAdvice(new MyControllerAdvice())

            //This also doesn't work
            //.setHandlerExceptionResolvers(createExceptionResolver())
            .build();
    }

    //This also did not work
    private ExceptionHandlerExceptionResolver createExceptionResolver() {
        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
            protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
                Method method = new ExceptionHandlerMethodResolver(MyControllerAdvice.class).resolveMethod(exception);
                return new ServletInvocableHandlerMethod(new MyControllerAdvice(), method);
            }
        };
        exceptionResolver.afterPropertiesSet();
        return …
Run Code Online (Sandbox Code Playgroud)

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

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

使用@SpringBootTest进行Spring Boot和Camel测试

我有spring boot app,有1.5.8版本的spring boot。 camel 2.20.1

简单路线:

@Component
public class MyRoute extends RouteBuilder {

  public static final String IN = "file://in";

  public static final String OUT = "file://out";

  @Override
  public void configure() throws Exception {
    from(IN).routeId("myId").to(OUT);
  }
}
Run Code Online (Sandbox Code Playgroud)

Und简单测试:

//@SpringBootTest
public class MyRouteTest extends CamelTestSupport {


      @Produce(uri = MyRoute.IN)
      private ProducerTemplate producerTemplate;

      @EndpointInject(uri = "mock:file:out")
      private MockEndpoint mockEndpointOut;

      @Override
      public String isMockEndpoints() {
        return "*";
      }

      @Test
      public void simpleTest() throws Exception {
        mockEndpointOut.expectedMessageCount(1);
        producerTemplate.sendBody("Test");
        mockEndpointOut.assertIsSatisfied();
      }

      @Override
      protected RoutesBuilder …
Run Code Online (Sandbox Code Playgroud)

java apache-camel spring-boot spring-boot-test spring-camel

6
推荐指数
2
解决办法
6803
查看次数

Spring-boot application-test.properties

我正在尝试使用junit对spring-boot应用程序进行单元测试.我已将application-test.properties放在src/test/resources下.我有一个ApplicationConfiguration类,它读取application.properties.

我的测试类看起来像这样

@RunWith(SpringRunner.class)
@SpringBootTest(classes=ApplicationConfiguration.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ActiveProfiles("test")
   public class TestBuilders {
      @Autowired
      private ApplicationConfiguration properties;
Run Code Online (Sandbox Code Playgroud)

当我尝试读取属性时,它始终为null.

我的ApplicationConfiguration类看起来像这样

@Configuration
@ConfigurationProperties
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource(value="file:config.properties", ignoreResourceNotFound = 
        true)})
public class ApplicationConfiguration{
    private xxxxx;
    private yyyyy;
Run Code Online (Sandbox Code Playgroud)

我尝试了所有可能的方法,我在谷歌上发现..没有运气.请帮忙!提前致谢.

spring-boot spring-boot-test application.properties

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

使用Spring Boot 1.5避免Kafka Streams开始测试

Spring Boot应用程序的测试过程中,我遇到了一个非常烦人的问题.我有一个使用Kafka Streams的应用程序,并在专用配置文件中声明它们.

@EnableKafka
@EnableKafkaStreams
@Configuration
public class KafkaStreamConfiguration {
    @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
    public StreamsConfig kStreamsConfigs() {
        // Omissis
    }
    @Bean
    public KStream<String, String> kStream() {
        // Omissis
    }
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序还使用Spring公开了一个专用的REST API @RestController.我想隔离测试这个休息控制器,如下所示.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class RestControllerTest {
    @Test
    public void someFancyTest() {
        // Omissis
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法避免Spring上下文启动KafkaStreamConfiguration类中定义的流.我没有找到任何方法在执行期间从Spring上下文中排除这个类RestControllerTest.

我不想KafkaEmbeddedRestControllerTest课堂上声明一个实例.在我看来这是胡说八道.

可能吗?如何切片测试以保持一定的独立性?

应用程序类尽可能简单.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, …
Run Code Online (Sandbox Code Playgroud)

java spring-boot apache-kafka-streams spring-kafka spring-boot-test

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

使用SpringRunner和PowermockRunner的异常

我正在尝试测试JavaMail api并使用SpringRunner和PowerMockRunner,但它失败了.

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PowerMockIgnore(value = {"javax.management.*"})
@SpringBootTest
public class BaseITest {

  @PrepareForTest(value = {MyStaticHelper.class})
  @Test
  public void testListFolders() {
     // mock static method
     // Use JavaMail API
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

javax.mail.MessagingException: java.security.NoSuchAlgorithmException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$DefaultSSLContext not a SSLContext
Run Code Online (Sandbox Code Playgroud)

如果我删除@PowerMockIgnore(value = {"javax.management.*"}),那么我收到此异常:

Caused by: java.lang.LinkageError: loader constraint violation: loader (instance of org/powermock/core/classloader/MockClassLoader) previously initiated loading for a different type with name "javax/management/MBeanServer"
Run Code Online (Sandbox Code Playgroud)

使用的依赖版本是:

  • powermock-api-mockito:1.7.1
  • powermock-module-junit4:1.7.1
  • mockito-all:2.0.2-beta
  • mockito-core:2.8.9

有人可以帮忙吗?

java jakarta-mail powermock powermockito spring-boot-test

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

Spring Boot单元测试未检测到自动接线组件的模块

我们将基于Maven的Spring Boot项目分为以下两个模块:

ProjectRoot
-SharedModel
-Application
--main
---java
----com....(Application.java)
-----com....(ClassToAutowire.java)
--test
----com....(ApplicationTest.java)
-----com....(ClassToAutowireTest.java)
Run Code Online (Sandbox Code Playgroud)

测试类如下所示:

@RunWith(SpringRunner.class)
public class ClassToAutowireTest extends BaseTest {

    @Autowired
    private ClassToAutowire classToAutowire;

    @Before
    public void setup() throws IOException {        
    ....
    }

    @Test
    public void someTest() {
        ....
        assertEquals(this.classToAutowire.isSupported(this.message), true);
    }

}
Run Code Online (Sandbox Code Playgroud)

ClassToAutowire如下所示:

@Component
public class ClassToAutowire {

    private ConfigurationService configurationService;

    @Autowired
    public ClassToAutowire(ConfigurationService configurationService) {
        this.configurationService = configurationService;
    }



    ....

}
Run Code Online (Sandbox Code Playgroud)

Application.java如下所示:

@SpringBootApplication
@EnableRetry
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
} …
Run Code Online (Sandbox Code Playgroud)

java intellij-idea spring-boot spring-boot-test

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

如何在@DataJpaTest中使用用户定义的数据库代理

我们需要跟踪数据库指标,因此我们使用 datasource-proxy 来跟踪它,以将其集成到我们创建的自定义数据源的 Spring Boot 项目中,如下所示

@Component
@Slf4j
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceBeanConfig
{

    public DataSource actualDataSource()
    {
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        return databaseBuilder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    @Primary
    public DataSource dataSource() {
        // use pretty formatted query with multiline enabled
        PrettyQueryEntryCreator creator = new PrettyQueryEntryCreator();
        creator.setMultiline(true);

        log.info("Inside Proxy Creation");

        SystemOutQueryLoggingListener listener = new SystemOutQueryLoggingListener();
        listener.setQueryLogEntryCreator(creator);

        return ProxyDataSourceBuilder
                .create(actualDataSource())
                .countQuery()
                .name("MyDS")
                .listener(listener)
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我们运行主应用程序时,数据源代理被拾取,但是当我们使用@DataJpaTest时,它没有被拾取。如何在 JUNIT 测试用例中启用数据源代理?

编辑::

使用SpringBeanPostProcessor配置Proxy DataSource

@Slf4j
@Configuration
public class DataSourceBeanConfig implements BeanPostProcessor …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-boot-test

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

在不加载应用程序上下文和不模拟真实测试环境的情况下执行 springboot 测试——这是可能的

我有个问题。请求您的帮助。我们有一个 Spring Boot 应用程序,我编写了没有 Mocks 的集成测试,而是使用TestRestTemplate@SpringbootTest.

因此,在本地计算机上,当我执行测试时,它们执行得很好,正如我MyApplication.class在里面给出的@SpringbootTest 那样,它将启动 spring 应用程序上下文并执行测试。

到这里一切都很好。

但我们将此应用程序部署在不同的测试环境(例如 qa、e2e、staging)上,然后部署在生产环境上。因此,我们必须针对上述环境执行 Jenkins 作业进行集成测试作为验收测试。

我在这里的问题是:

  • 当我在 jenkins 上执行这些测试时,测试在 Jenkins Slave 机器上执行(在可用执行器中随机选择),它将到达端点(qa 或 e2e 或登台或生产端点)并发送其余请求并获取响应并验证。但是测试启动詹金斯从机上的应用程序上下文并加载到随机端口上,并且将在詹金斯从机上可用,直到测试完成,尽管我根本不与应用程序上下文交互(因为我正在点击外部测试结束)点)。 当我尝试对真实测试服务器运行测试时,是否有任何选项不加载 spring 应用程序上下文,并在本地测试时加载应用程序上下文?

请帮助..我是 Spring Boot 的新手,被困在这里。

预先非常感谢

spring-boot-test

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

SpringBoot项目的单元测试中无法注入@Service

我有一个@Service,我试图在单元测试中模拟它,但到目前为止我得到一个空值。在应用程序类中,我指定什么是 scanBasePackages。我必须以不同的方式做到这一点吗?谢谢。

\n\n

这是我实现接口的服务类:

\n\n
@Service\npublic class DeviceService implements DeviceServiceDao {\n\nprivate List<Device> devices;\n\n@Override\npublic List<Device> getDevices(long homeId) {\n    return devices;\n}\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的单元测试。

\n\n
public class SmartHomeControllerTest {\n\n    private RestTemplate restTemplate = new RestTemplate();\n    private static final String BASE_URL = \xe2\x80\x9c..\xe2\x80\x9d;\n\n    @Mock\n    private DeviceService deviceService;\n\n@Test\npublic void getHomeRegisteredDevices() throws Exception {\n\n    Device activeDevice = new DeviceBuilder()\n            .getActiveDevice(true)\n            .getName("Alexa")\n            .getDeviceId(1)\n            .getHomeId(1)\n            .build();\n    Device inativeDevice = new DeviceBuilder()\n            .getInactiveDevice(false)\n            .getName("Heater")\n            .getDeviceId(2)\n            .getHomeId(1)\n            .build();\n\n    UriComponentsBuilder builder = UriComponentsBuilder\n            .fromUriString(BASE_URL + "/1/devices");\n\n    List response = restTemplate.getForObject(builder.toUriString(), List.class);\n\n …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-boot-test

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