spring-boot - Spring Boot 2 找不到 @Test(expected = xxx)
问题描述
爪哇 1.8
在我的 Spring Boot 2 项目中:
构建.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.h2database:h2'
implementation 'javax.servlet:jstl:1.2'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'junit:junit:4.4'
}
test {
useJUnitPlatform()
}
在我的测试中:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class CategoryTest {
@Autowired
private CategoryRepository categoryRepository;
@Test
public void myTest() {
categoryRepository.save(new Category());
}
@Test(expected = javax.validation.ConstraintViolationException.class)
public void shouldNotAllowToPersistNullProperies() {
categoryRepository.save(new Category());
}
}
测试myTest()
成功,但我在测试中得到编译错误shouldNotAllowToPersistNullProperies()
:
error: cannot find symbol
@Test(expected = javax.validation.ConstraintViolationException.class)
^
symbol: method expected()
location: @interface Test
解决方案
您可以使用 JUnit 5 而不是 JUnit 4。
消除:
testImplementation 'junit:junit:4.4'
JUnit 5 不知道“预期”,而是使用 assertThrows 像这样:
@Test
public void shouldNotAllowToPersistNullProperies() {
Assertions.assertThrows(ConstraintViolationException.class, () -> {
categoryRepository.save(new Category());
});
}
推荐阅读
- r - 如何使用 R 用特定的搜索条件抓取 Google?
- c++ - 如何在 OpenGL 中正确旋转和缩放对象?
- editor - 维基文本的编辑器
- python - 我想扩展我的代码,但我不知道该怎么做
- javascript - 从#each 输入列表中获取特定用户
- sql - SQL 查询没有结果
- javascript - 计算响应式标题的高度并以另一个 div 高度的样式使用结果
- c# - IIS 10 灾难性故障(来自 HRESULT 的异常:0x8000FFFF (E_UNEXPECTED))
- java - Stream.dropWhile() 不会以两个不同的值返回正确的值
- c# - 从类型的成员中获取属性的通用方法