Spring Boot 2找不到@Test(expected = xxx)

问题描述 投票:0回答:1

java 1.8

在我的Spring Boot 2项目中:

build.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
spring-boot junit4
1个回答
0
投票

您可以使用JUnit 5而不是JUnit 4。

删除:

testImplementation 'junit:junit:4.4'

JUnit 5不知道“期望”,相反,我们使用assertThrows这样子:

@Test
public void shouldNotAllowToPersistNullProperies() {

    Assertions.assertThrows(ConstraintViolationException.class, () -> {
        categoryRepository.save(new Category());
    });

}
© www.soinside.com 2019 - 2024. All rights reserved.