我有一个使用spring-boot版本的spring-boot应用程序1.5.9.RELEASE.要测试这个应用程序,我想使用junit-jupiter版本5.0.2.
对于简单的服务测试,它没有任何问题.但是当谈到测试休息端点时,我失败了.原因是@RunWith(SpringRunner.class)注释,我使用junit4将所有内容连接在一起.
SpringRunner在spring-boot 2之前有junit5吗?
更新
是否有可能以某种方式拥有相同的测试类@MockBean和@Autowired相同的服务?
换句话说,我只想@MockBean为一项测试提供服务,而对于同一类别的其他测试,我需要它作为@Autowired.
我有在内存数据库上执行的集成测试.每个测试的签名看起来或多或少都像这样:
@RunWith(SpringRunner.class)
@SpringBootTest
@Sql("/clean-data-in-all-tables.sql")
public class SomeTest {
@Test
public void shouldDoSomehting() {}
}
Run Code Online (Sandbox Code Playgroud)
在测试上下文初始化期间,Hibernate会重新创建数据库模式:
spring:
jpa:
hibernate:
ddl-auto: create-drop
Run Code Online (Sandbox Code Playgroud)
我希望在初始化上下文之后和生成数据库模式之后执行sql脚本.但是在某些情况下clean-data-in-all-tables.sql,在生成模式之前执行它会失败,因为它需要尚未创建的表.
我按照我解释的方式编写了500多个测试,并且它们都运行良好,直到我添加了更多类似的测试.
当我通过Gradle或IntelliJ一起执行测试时,测试失败.请注意,失败的测试不是最近添加的测试.这是与我添加的测试完全无关的旧测试.同样奇怪的是,如果我通过IntelliJ 一个接一个地运行它们,那么失败的测试工作得很好.
它看起来像一个弹簧启动的错误,但我仍然试图找到一种方法来解决它.与此同时,我尝试了许多方法来解决这个问题,但是没有一个是有用的.
请分享您对可能有用的内容以及我的代码可能出现的问题的想法.
更新:
找到了解决方法:改变spring.jpa.hibernate.ddl-auto从create-drop以create解决问题.
但问题仍然是开放这种奇怪行为的原因是什么?
我正在尝试使用SpringBoot,SpringDataJpa以及使用SpringBootTest进行单元测试的ManyToOne双向关联.但是,测试失败,堆栈跟踪如下所示.但是我无法找到原因.任何指针都会有所帮助
Spring Boot JUnit Test下面的ManyToOne双向关联失败.
@Test
public void testFindByRegionIdEquals() {
Region region = regionService.findByRegionIdEquals(1L);
Region expectedRegion = new Region(1L, "Europe");
assertThat(region).isNotNull().isEqualTo(expectedRegion);
assertThat(region.getCountries()).isNotEmpty().doesNotContainNull().size().isEqualTo(8);
}
Run Code Online (Sandbox Code Playgroud)
异常StackTrace
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: zikzakjack.domain.Region.countries, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:204)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:148)
at org.hibernate.collection.internal.PersistentSet.isEmpty(PersistentSet.java:149)
at org.assertj.core.util.IterableUtil.isNullOrEmpty(IterableUtil.java:35)
at org.assertj.core.internal.Iterables.assertNotEmpty(Iterables.java:152)
at org.assertj.core.api.AbstractIterableAssert.isNotEmpty(AbstractIterableAssert.java:145)
at zikzakjack.service.RegionServiceTests.testFindByRegionIdEquals(RegionServiceTests.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Run Code Online (Sandbox Code Playgroud)
拥有实体ManyToOne
@Data
@Entity
@Table(name = "COUNTRIES")
public class Country implements Serializable, Comparable<Country> {
private static final long serialVersionUID = 1L; …Run Code Online (Sandbox Code Playgroud) 我正在编写一个控制器测试,其中控制器看起来像
@RestController
public class VehicleController {
@Autowired
private VehicleService vehicleService = null;
...
}
Run Code Online (Sandbox Code Playgroud)
虽然测试类看起来像
@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {
@Autowired
private MockMvc mockMvc = null;
@MockBean
private VehicleService vehicleServie = null;
@Test
public void test() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行此测试时,它失败并出现以下错误
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.database.repositories.SomeOtherRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Run Code Online (Sandbox Code Playgroud)
这里,SomeOtherRepository不在给定的控制器或服务中使用。
如果我这样做@MockBean测试SomeOtherRepository有效,但其余存储库也会出现同样的问题。
@MockBean private SomeOtherRepository someOtherRepository = null
... …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Spring Boot 项目中加载 application.properties 进行测试。我正在使用 @DataJpaAnnotation 以及我的自定义 application.properties 文件。
这是我的示例配置如下
@DataJpaTest
@RunWith(SpringRunner.class)
@SqlGroup({
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {
"classpath:sql/dont-use-cascadeType-remove/before.sql" }),
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = {
"classpath:sql/dont-use-cascadeType-remove/after.sql" }) })
@TestPropertySource(locations = { "classpath:application.properties" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Slf4j
public class BookCategoryRepositoryTest {
Run Code Online (Sandbox Code Playgroud)
我能够成功执行测试用例,但是当我验证日志时,我的应用程序正在采用嵌入的 H2 Db URL,而不是我在 application.properties 文件中提到的 URL。
从我发现的日志中
embedded database: url='jdbc:h2:mem:69b49362-3f83-4e79-9f35-b0deb5e744f2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
Run Code Online (Sandbox Code Playgroud)
我的属性文件包含
spring.datasource.url=jdbc:p6spy:mem:jpa-best-practices;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=db-user
spring.datasource.password=db-password
Run Code Online (Sandbox Code Playgroud)
不知道为什么会发生这种情况,我无法找到解决方案。请帮忙。
spring spring-data spring-data-jpa spring-boot spring-boot-test
我写了 spring boot 集成测试,它正在工作。这是测试配置:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureMockMvc
@Transactional
public class SomeTest {
@Autowired
private MockMvc mvc;
@Test
public void insertEventTest(){
...testing something...
}
}
Run Code Online (Sandbox Code Playgroud)
我知道在设置webEnvironment = RANDOM_PORTspring 时将初始化嵌入式 Web 服务器并针对该 Web 服务器运行此测试。我在运行此测试时查看了日志,发现嵌入式TomcatWebServer已启动。初始化 Tomcat 大约需要 6 秒,但在日志的这两个部分之间,很少有其他 bean 被初始化,所以我很确定初始化 Tomcat 不是 6 秒,而是不到 6 秒。日志的一部分:
2019-10-13 16:03:20.065 INFO 8596 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2019-10-13 16:03:20.098 INFO 8596 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-10-13 16:03:20.098 INFO …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Spring Boot 应用程序。对于我的常规服务类单元测试,我可以使用 扩展我的测试类MockitoExtension,并且模拟很严格,这就是我想要的。
interface MyDependency {
Integer execute(String param);
}
class MyService {
@Autowired MyDependency myDependency;
Integer execute(String param) {
return myDependency.execute(param);
}
}
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
MyDependency myDependency;
@InjectMocks
MyService myService;
@Test
void execute() {
given(myDependency.execute("arg0")).willReturn(4);
myService.execute("arg1"); //will throw exception
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,将引发异常并显示以下消息(已编辑):
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'execute' method:
myDependency.execute(arg1);
- has following stubbing(s) with different arguments:
1. myDependency.execute(arg0);
Run Code Online (Sandbox Code Playgroud)
此外,如果从未使用过存根,则会出现以下内容(已编辑):
org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected. …Run Code Online (Sandbox Code Playgroud) 在为elasticserach启动testcontainer时,出现“ContainerLaunchException:等待日志输出匹配超时”。我应该如何解决这个问题?
container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
.withEnv("discovery.type", "single-node")
.withExposedPorts(9200);
container.start();
Run Code Online (Sandbox Code Playgroud)
12:16:50.370 [主要]错误[docker.elastic.co/elasticsearch/elasticsearch:7.16.3] - 无法启动容器org.testcontainers.containers.ContainerLaunchException:等待日志输出匹配'超时。(“消息”:\ s?“开始”。 |]开始$)'在org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy.waitUntilReady(LogMessageWaitStrategy.java:49)在org.testcontainers.containers.wait.strategy。 AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:51)
更新:我研究了构造函数 ElasticsearchContainer
public ElasticsearchContainer(DockerImageName dockerImageName) {
super(dockerImageName);
this.caCertAsBytes = Optional.empty();
dockerImageName.assertCompatibleWith(new DockerImageName[]{DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME});
this.isOss = dockerImageName.isCompatibleWith(DEFAULT_OSS_IMAGE_NAME);
this.logger().info("Starting an elasticsearch container using [{}]", dockerImageName);
this.withNetworkAliases(new String[]{"elasticsearch-" + Base58.randomString(6)});
this.withEnv("discovery.type", "single-node");
this.addExposedPorts(new int[]{9200, 9300});
this.isAtLeastMajorVersion8 = (new ComparableVersion(dockerImageName.getVersionPart())).isGreaterThanOrEqualTo("8.0.0");
String regex = ".*(\"message\":\\s?\"started\".*|] started\n$)";
this.setWaitStrategy((new LogMessageWaitStrategy()).withRegEx(regex));
if (this.isAtLeastMajorVersion8) {
this.withPassword("changeme");
}
}
Run Code Online (Sandbox Code Playgroud)
它使用 setWaitStrategy。所以我更新了我的代码如下
container.setWaitStrategy((new LogMessageWaitStrategy()).withRegEx(regex).withTimes(1));
Run Code Online (Sandbox Code Playgroud)
但我仍然遇到同样的错误。这是日志消息的发送范围。
再次更新:我意识到上面的代码更改不会更新任何默认值。
这是新的变化:
container.setWaitStrategy((new LogMessageWaitStrategy())
.withRegEx(regex)
.withStartupTimeout(Duration.ofSeconds(180L)));
Run Code Online (Sandbox Code Playgroud)
它适用于这个新的变化。我必须从 …
elasticsearch spring-boot-test testcontainers testcontainers-junit5
我正在尝试利用 H2 进行测试并在 中有以下配置src/test/resources/application.yaml:
spring:
r2dbc:
url: r2dbc:h2:file://testdb
Run Code Online (Sandbox Code Playgroud)
我有一个带有注释的空测试,@SpringBootTest但是当我运行它时,出现以下错误:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.r2dbc.pool.ConnectionPool]: Factory method 'connectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Unable to create a ConnectionFactory for 'ConnectionFactoryOptions{options={driver=h2, protocol=file, host=testdb}}'. Available drivers: [ pool, postgresql, h2 ]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 131 common frames omitted
Caused by: java.lang.IllegalStateException: Unable to create a ConnectionFactory for 'ConnectionFactoryOptions{options={driver=h2, protocol=file, host=testdb}}'. Available drivers: [ pool, postgresql, h2 ]
at io.r2dbc.spi.ConnectionFactories.get(ConnectionFactories.java:145)
at org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBuilder.build(ConnectionFactoryBuilder.java:125)
at org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryConfigurations.createConnectionFactory(ConnectionFactoryConfigurations.java:56)
at …Run Code Online (Sandbox Code Playgroud) spring-boot-test ×10
spring-boot ×6
java ×4
junit ×2
mockito ×2
spring ×2
h2 ×1
junit-runner ×1
junit5 ×1
r2dbc ×1
spring-data ×1
spring-mvc ×1
testing ×1
unit-testing ×1