标签: spring-boot-test

带有 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
查看次数

使用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
查看次数

使用@SpringBootTest禁用数据库连接

我有一个带有休眠功能的 SpringBoot 应用程序。在我的测试中,我想禁用任何类型的数据库连接和配置(测试无权访问数据库)。我该怎么办呢?

我的测试类带有注释@SpringBootTest并具有@Autowired属性。禁用所有数据库交互的正确注释值是什么?

@SpringBootTest
class MyTest {

  @Autowired
  ....
}

Run Code Online (Sandbox Code Playgroud)

hibernate jpa spring-boot-test

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

春天奇怪地取决于班级位置

我有一个SpringBootTest测试应该依赖一个单独的类来设置嵌入式 Postgres 和数据源。

因此 Repository 配置如下所示:

package com.stream.repository.configuration
@Configuration
@ComponentScan(basePackages = arrayOf("com.stream.repository"))
@EntityScan(basePackages = arrayOf("com.stream.repository"))
@EnableJpaRepositories(basePackages = arrayOf("com.stream.repository"))
@EnableAutoConfiguration
class RepositoryConfiguration {
Run Code Online (Sandbox Code Playgroud)

测试类如下所示:

package com.stream.webapp.rest
@AutoConfigureMockMvc(addFilters = false)
@SpringBootTest(properties =
[
    "spring.jpa.hibernate.ddl-auto=validate",
    "spring.jpa.show-sql=true",
    "spring.liquibase.enabled=true",
    "spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yml",
    "spring.jpa.properties.hibernate.jdbc.time_zone=UTC"
],
        classes = [RepositoryConfiguration::class, AuditController::class],
        webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class AuditControllerTest {
Run Code Online (Sandbox Code Playgroud)

这就是它变得奇怪的地方。如果我使用该配置运行,它会抱怨找不到EntityManagerFactory

AuditService 需要一个无法找到的类型为“javax.persistence.EntityManagerFactory”的 bean。

经过一番折腾,我找到了解决这个问题的办法。如果我移动它RepositoryConfiguration以便它在包中com.stream.webapp.rest,即与AuditControllerTest它一样神奇地工作。

我似乎找不到任何理由说明为什么会这样。那么任何人都可以解释它并且有办法解决它吗?因为我不想动它。把它放在哪里很有意义。

作为旁注,它是用 Kotlin 编写的,但我不明白为什么在这种情况下它很重要。而这仅用于测试。在测试范围之外运行应用程序时,它可以工作

我还可以补充一点,AuditControllerTest它在一个模块中,RepositoryConfiguration在另一个模块中。如果将其放置在“正确”的包中(仍然是单独的模块),则不确定它是否相关,因为它可以工作

问题的 TL; DR:为什么 spring 关心 …

java testing kotlin spring-boot spring-boot-test

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

从 SpringBootTest 中排除 Configuration 类

我有一个类在 src/main/java 下配置 Kafka:

@Configuration
public class SenderConfig {

    @Value("${spring.kafka.producer.bootstrap-servers}")
    private String bootstrapServers;


    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Bean
    public ProducerFactory<String,Item> producerFactory(){
        log.info("Generating configuration to Kafka key and value");
        Map<String,Object> config = new HashMap<>();
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapServers);
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory(config);
    }
Run Code Online (Sandbox Code Playgroud)

我在 src/test/java 下有一个类来测试存储库,我想排除此配置类:

@SpringBootTest(properties = { "spring.cloud.config.enabled=false",
        "spring.autoconfigure.exclude=com.xyz.xyz.config.SenderConfig" })
@Sql({ "/import_cpo_workflow.sql" })
public class WorkflowServiceTest {

    @Autowired
    private WorkflowRep workflowRep;

    @Test
    public void testLoadDataForTestClass() {
        assertEquals(1, workflowRep.findAll().size());
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:由以下原因引起:java.lang.IllegalStateException:无法排除以下类,因为它们不是自动配置类:com.xyz.xyz.config.SenderConfig

既然我现在没有测试 Kafka,如何从我的测试中排除这个配置类?

spring spring-boot-test

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

在 Spring boot 测试中使用 @Nested 类时,Mockito 不会重置

再次阅读 JUnit 文档后,我发现使用@Nested内部类对测试进行分组并最终在测试报告中以树形结构显示它们是很好的。

但是当我PostController像这样重构时。

@WebFluxTest(
        controllers = PostController.class,
        excludeAutoConfiguration = {
                ReactiveUserDetailsServiceAutoConfiguration.class, ReactiveSecurityAutoConfiguration.class
        }
)
@Slf4j
@DisplayName("testing /posts endpoint")
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class PostControllerTest {

    @Autowired
    private WebTestClient client;

    @MockBean
    private PostRepository posts;

    @MockBean
    private CommentRepository comments;

    @BeforeAll
    public static void beforeAll() {
        log.debug("before all...");
    }

    @AfterAll
    public static void afterAll() {
        log.debug("after all...");
    }

    @BeforeEach
    public void beforeEach() {
        log.debug("before each...");
    }

    @AfterEach
    public void afterEach() {
        log.debug("after each...");
    }

    @Nested
    @DisplayName("/posts GET")
    class GettingAllPosts { …
Run Code Online (Sandbox Code Playgroud)

mockito spring-boot junit5 spring-boot-test

6
推荐指数
0
解决办法
1323
查看次数

如何在 JUnit 5 下进行 Spring Boot Test 解析 YAML 文件上外部化的缩进/分层属性

如何在 YAML 文件上解析缩进/分层属性Spring Boot TestJUnit 5

我想编写测试来验证一些依赖于Environment.getProperty(String key)的逻辑:

@ExtendWith(SpringExtension.class)
class PropertiesReolution_SO_IT {

    @Nested
    @TestPropertySource(locations = "classpath:application-test.yml")
    public class ViaYamlFile {

        @Autowired
        private Environment env;

        @Test
        void testGetDottedHierarchicalProperty() throws Exception {
            final String key = "dotted.hierarchical.property";
            assertNotNull(this.env.getProperty(key));
            assertEquals("application-test.yml", this.env.getProperty(key));
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

dotted.hierarchical.property属性在 YAML 文件中定义application-test.yml如下:

@ExtendWith(SpringExtension.class)
class PropertiesReolution_SO_IT {

    @Nested
    @TestPropertySource(locations = "classpath:application-test.yml")
    public class ViaYamlFile {

        @Autowired
        private Environment env;

        @Test
        void testGetDottedHierarchicalProperty() throws Exception {
            final String key = "dotted.hierarchical.property"; …
Run Code Online (Sandbox Code Playgroud)

java spring-boot junit5 spring-boot-test

6
推荐指数
0
解决办法
547
查看次数

如何为MockServer的同一个请求设置不同的响应?

我在为具有完全相同的请求的多个响应设置 MockServerClient 时遇到问题。

我读到,带着对“时代”的期望,这可能会完成,但我无法使它适合我的场景。

如果您使用此 JSON 调用服务(两次):

{
    "id": 1
}
Run Code Online (Sandbox Code Playgroud)

第一个响应应该是“passed true”,第二个响应“passed false”

回应1:

{
    "passed":true
}
Run Code Online (Sandbox Code Playgroud)

回应2:

{
    "passed":false
}
Run Code Online (Sandbox Code Playgroud)

我设置了第一个请求,但如何设置第二个请求?

import com.nice.project.MyService;
import com.nice.project.MyPojo;
import org.mockito.Mock;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.matchers.TimeToLive;
import org.mockserver.matchers.Times;
import org.mockserver.model.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.when;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static …
Run Code Online (Sandbox Code Playgroud)

java spring unit-testing mockserver spring-boot-test

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

Spring Boot 属性值从 String 到 Duration 的转换在应用程序中有效,但在单元测试中失败

根据 spring 文档,诸如 之类的字符串属性值10s将被正确转换为java.time.Duration.

事实上,这对我来说适用于主要的应用程序属性。但它在单元测试中失败了。

单元测试

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties(value = MyConfig.class)
@TestPropertySource("classpath:test.properties")
public class MyUnitTest {
    @Autowired
    MyConfig config;
...
}
Run Code Online (Sandbox Code Playgroud)

配置类

@ConfigurationProperties(prefix = "my")
@Component
public class MyConfig {

    @Value("${my.failed-duration}")
    public Duration myDuration;
...
}
Run Code Online (Sandbox Code Playgroud)

测试.属性

my.failed-duration=10s
Run Code Online (Sandbox Code Playgroud)

例外

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:350)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:355)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$7(ClassBasedTestDescriptor.java:350)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) …
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-properties spring-boot-test

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