标签: spring-boot-test

如何在没有嵌入数据源配置的情况下在 spring 启动测试期间执行`schema.sql`?

有一个带有 h2 数据库的 spring boot 应用程序,用作主数据库。还有一个resource/schema.sql在启动时通过 spring boot 加载的。

但是在使用@SpringBootTestspring boot 的集成测试期间不会加载这个schema.sql。相反,它需要在h2已经有db 的情况下设置嵌入式数据库。

有没有办法在schema.sql没有嵌入数据源配置的情况下执行?并且只对所有测试执行一次(例如@Sql,用于所有测试的模式创建不是解决方案)?

java spring embedded-database spring-boot spring-boot-test

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

如何在Mockito测试中修复RestTemplate.exchange的空值响应?

我的服务类如下,其后是测试 -

@Service
public class MyServiceImpl implements MyService {

        @Autowired
        private RestTemplate restTemplate;

        @Override
        public StudentInfo getStudentInfo(String name) {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

            HttpEntity entity = new HttpEntity(headers);

            StudentInfo student = null;

            URI uri = new URI("http:\\someurl.com");             

           ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
                        HttpMethod.GET, entity,
                        String.class);

           if (responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)) {
                   throw new Exception("Student absent");
            }else {
              ObjectMapper mapper = new ObjectMapper();
              StudentInfo student = mapper.readValue(responseEntity.getBody(), StudentInfo.class);

           }

            return student;
        }
    }
Run Code Online (Sandbox Code Playgroud)

测试类:在我下面的测试类中,我看到ResponseEntity对象在调试时为null,导致NPE.

@RunWith(MockitoJUnitRunner.class)
public class MyServiceImplTest {

    @InjectMocks
    private MyService …
Run Code Online (Sandbox Code Playgroud)

junit spring-test mockito spring-boot spring-boot-test

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

使用 Spring Boot 测试时不想加载 application.yml

如何告诉 Spring 只加载 application-test.yml 而不是 application.yml 文件?

我有一个配置类:

@ActiveProfiles("test")
@SpringBootConfiguration

public class MongoTestConfig {

    @Autowired
    MongoOperations operations;
...
}
Run Code Online (Sandbox Code Playgroud)

和一个测试类:

@RunWith(SpringRunner.class)
@DataMongoTest
@SpringBootTest(classes = MongoTestConfig.class)
public class TagDefinitionRepositoryTest {
...
@Test
....
}
Run Code Online (Sandbox Code Playgroud)

我试图添加:

@TestPropertySource(locations = {"classpath:application-test.yml"})
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
Run Code Online (Sandbox Code Playgroud)

到我的配置类,但它不起作用:Spring 仍然加载 application.yml

spring-test spring-boot spring-boot-test

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

使用 Hibernate Search 时由于 lucene 锁定,Spring Boot 集成测试失败

在我的 Spring Boot 1.5.10.Final 项目中,我使用 Hibernate Search ORM 5.6.4.Final。除了集成测试之外,它运行良好。有一个测试类有多种测试方法来测试搜索逻辑。如果我只运行这个测试类,一切都会正常。Spring Boot 正在启动并创建索引。如果我将这个测试类与所有其他集成测试一起运行,每个测试类都会抛出 LockObtainFailedException 并且 Hibernate Search 测试将失败。

org.apache.lucene.store.LockObtainFailedException: Lock held by this virtual machine: ...LieferantEntity\write.lock
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:127) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:776) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:126) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:92) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:117) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:203) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:81) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:165) …
Run Code Online (Sandbox Code Playgroud)

hibernate-search spring-boot spring-boot-test

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

没有可用的“org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext”类型的合格 bean

我正在使用 webflux 和 springboottest 在 spring boot 中运行测试。

 buildscript {
    ext {
        springBootVersion = '2.0.5.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


ext {
    springCloudVersion = 'Finchley.SR1'
}

dependencies {
    compile('org.junit.jupiter:junit-jupiter-api')
    compile('org.springframework.boot:spring-boot-starter-webflux')
   testCompile('org.springframework.boot:spring-boot-starter-test')
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
    testCompile('io.projectreactor:reactor-test')

}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}
Run Code Online (Sandbox Code Playgroud)

测试用例

@SpringBootTest
@ExtendWith({SpringExtension.class})

class DemoTest {

    private WebTestClient …
Run Code Online (Sandbox Code Playgroud)

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

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

Junit5 Spring Boot Autowire ComponentScan 不工作

我的问题:如果我的测试引用@Bean中列出的类中的声明,则@SpringBootTest自动装配工作。如果它引用@ComponentScan由 中列出的类自动连接的类@SpringBootTest,则自动装配失败。在测试之外,我的应用程序启动时没有自动装配或组件扫描问题,并且我可以确认我要在测试中加载的服务在非测试中运行良好。我很沮丧。我坏了,还是 Spring Boot 2 上的 Junit5 功能?

我的测试:

@ExtendWith(SpringExtension.class)
@SpringBootTest (classes=MyConfig.class)
public class MyTest {
    // fails to autowire
    @Autowired
    private MyService _mySvc ;

    // succeeds!
    @Autowired @Qualifier ( "wtf" )
    private String _wtf ;
Run Code Online (Sandbox Code Playgroud)

我的配置:

@EnableWebMvc
@SpringBootApplication ( scanBasePackages = "my.packaging" )
@Configuration
public class MyConfig {

    @Bean
    public String wtf ( ) { return "W T F???" ; }

    // No @Bean for MyService because component scan is nicer …
Run Code Online (Sandbox Code Playgroud)

java spring junit5 spring-boot-test

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

Spring boot:@ConfigurationProperties 对测试不满意

我在测试执行中遇到此异常:

UnsatisfiedDependencyException:创建名为“net.gencat.transversal.espaidoc.mongo.GridFSTest”的bean时出错:通过字段“resourceProperties”表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“net.gencat.transversal.espaidoc.ResourcesConfigProperties”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。

所以,我认为信息是如此清楚不过了:ResourcesConfigProperties is not satisfied

我的测试:

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

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private ResourcesConfigProperties resourceProperties;

    public URL getHugeResource() {
        try {
            return Paths
                .get(this.resourceProperties.getHuge())
                .toUri()
                .toURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }

    @Test
    public void storeHugeFile() throws IOException {
        URL resource = this.getHugeResource();

        this.gridFsTemplate.store(
            resource.openStream(),
            resource.getPath(),
            "mime"
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

并且ResourcesConfigProperties是:

@ConfigurationProperties(prefix = "files")
public class ResourcesConfigProperties {

    private String huge; …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-boot-test

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

Spring boot 2.0.5.RELEASE - sleuth 和mockito

我已经尝试解决这个问题一周了,但一点运气都没有。问题出在单元测试上。

这是我要测试的课程:

import brave.Span;
import brave.Tracer;

@Service
public class InternetBackEndRestClient {

    @Autowired
    private Tracer tracer;

  public PasswordJwtResponse generatePassworJwt(PasswordJwtRequest passwordJwtRequest, String traceId) throws LogonProxyException {
      log.info("{\"Starting method\": \"generatePassworJwt\", \"input\": {} }", passwordJwtRequest);

    Span newSpan = tracer.nextSpan().name("spanPasswordJwtResponse");
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能进行单元测试?Brave.Tracer 是最后一堂课,因此我无法嘲笑它。无论如何要设置上下文吗?或模拟追踪器?

@RunWith(MockitoJUnitRunner.class)
public class InternetBackEndRestClientTest {

   @InjectMocks
   private InternetBackEndRestClient internetBackEndRestClient; 

   @Mock
   private Tracer tracer; 

   @Test
   public void generatePassworJwt_test() { 
      internetBackEndRestClient.generatePassworJwt(...);
      ....
   }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

mockito spring-boot spring-cloud-sleuth spring-boot-test

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

在 ServletContext 中找不到属性 ServerContainer

在我的 Spring Boot 应用程序中,我也使用了 websockets。一切正常,正如在生产中预期的那样。

现在我开始使用 Spring-Boot-Test 创建单元测试。

每次我启动 @SpringBootTest 时,都会遇到以下异常(缩短):

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'createWebSocketContainer' defined in class path resource [com/package/spring/ws/MyWebsocketConfig.class]: Invocation of init method failed;
Caused by: java.lang.IllegalStateException: Attribute 'javax.websocket.server.ServerContainer' not found in ServletContext
Run Code Online (Sandbox Code Playgroud)

长版

java.lang.IllegalStateException: Failed to load ApplicationContext

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-websocket spring-boot-test tomcat9

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

如何在spring-boot中使用resttemplate模拟调用另一个服务的服务?

各位专家下午好,

我有一个要求,我将调用 3 个 REST API 的顺序调用作为单个客户端调用 GET /offers 的一部分,以检索百货商店不同通道中每种产品的可用报价,如下所示

  1. 获取百货商店的所有过道/aisels
  2. 获取通道 /aisles/{aisleID}/products 中的所有产品
  3. 获取产品 /product/{productId/offers 的所有报价

    @Service使用 RestTemplate 交换方法在我的类中执行此操作:

    ResponseEntity aisles=restTemplate.exchange(url, HttpMethod.GET, requestEntity, Aisles.class);

aisleId然后循环检索每个产品并调用第二个 API 来获取产品

ResponseEntity<Products> products= restTemplate.exchange(url,
                    HttpMethod.GET, requestEntity, Products.class);
Run Code Online (Sandbox Code Playgroud)

productId然后循环检索每个并调用第三个 API 来获取 Offers

最后整理所有回复,将报价列表发送给客户。

现在,我对用于编写 JUnit 的 mockito 框架很陌生。我的服务类有一个名为retrieveAllOffers() 的方法,其中有如上所述的 3 个交换方法。

我想知道如何在 Junit 中模拟这 3 个调用才能获得成功的响应场景。

非常感谢您的帮助。

junit mockito spring-boot-test

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