怎么用Spring数据测试ExpectedException-未引发异常
问题描述
我已经在我的学习项目中创建了一些测试,但是ExpectedException无法按预期方式工作。我正在做一个没有名称的简单保存(应该抛出异常),并且没有抛出任何内容。
OBS:
-
当我将spring-boot-starter-parent从“ 2.1.12.RELEASE”更改为“ 1.5.4.RELEASE”有效。但我真的很想知道为什么。
-
我已经尝试过从“ javax.validation.constraints.NotEmpty”中使用NotEmpty“
谢谢!
------------ Student.java ------------
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Student extends AbstractEntity{
public Student() {
}
public Student(String name, String email) {
this.name = name;
this.email = email;
}
@NotEmpty(message = "O campo nome do estudante é obrigatório")
private String name;
@NotEmpty
@Email
// @Column(columnDefinition = "varchar(255) default 'John Snow'")
private String email;
------------ StudentRepository.java ------------
import br.com.devdojo.awesome.model.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface StudentRepository extends PagingAndSortingRepository {
List findByNameIgnoreCaseContaining(String name);
}
------------ StudentRepositoryTest.java ------------
import static org.assertj.core.api.Assertions.*;
@RunWith(SpringRunner.class)
@DataJpaTest
public class StudentRepositoryTest {
@Autowired
private StudentRepository studentRepository;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenNameIsNullShouldThrownConstraintViolationException() {
thrown.expect(ConstraintViolationException.class);
thrown.expectMessage("O campo nome do estudante é obrigatório");
this.studentRepository.save(new Student());
}
------------ POM文件------------
4.0.0 groupId Projects 1.0-SNAPSHOT org.apache.maven.plugins maven-compiler-plugin 8 jar org.springframework.boot spring-boot-starter-parent 2.1.12.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-security org.springframework.security spring-security-test 4.2.3.RELEASE test com.oracle ojdbc8 1.0 system C:/sqldeveloper/jdbc/lib/ojdbc8.jar mysql mysql-connector-java runtime 8.0.13 commons-io commons-io 2.5 com.h2database h2 test org.springframework.boot spring-boot-starter-test 1.5.4.RELEASE test
------------错误消息------------
2020-02-24 15:16:01.788 INFO 16196 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.15.Final}
2020-02-24 15:16:01.790 INFO 16196 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-02-24 15:16:01.997 INFO 16196 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-02-24 15:16:02.216 INFO 16196 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: create table spring_user (id bigint not null, admin boolean not null, name varchar(255) not null, password varchar(255) not null, user_name varchar(255) not null, primary key (id))
Hibernate: create table student (id bigint not null, email varchar(255), name varchar(255), primary key (id))
Hibernate: alter table spring_user drop constraint if exists UK_6p8pvty87x0ovxe0v5ght3l3r
Hibernate: alter table spring_user add constraint UK_6p8pvty87x0ovxe0v5ght3l3r unique (user_name)
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
2020-02-24 15:16:03.166 INFO 16196 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-24 15:16:03.721 INFO 16196 --- [ main] b.c.d.awesome.StudentRepositoryTest : Started StudentRepositoryTest in 5.05 seconds (JVM running for 6.214)
2020-02-24 15:16:03.745 INFO 16196 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@25ce9dc4 testClass = StudentRepositoryTest, testInstance = br.com.devdojo.awesome.StudentRepositoryTest@742ff096, testMethod = createWhenEmailIsNullShouldThrownConstraintViolationException@StudentRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@74ea2410 testClass = StudentRepositoryTest, locations = '{}', classes = '{class br.com.devdojo.awesome.ApplicationStart}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@17f62e33 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3eb738bb, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@185a6e9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@49438269, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@36807d48, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6f4a47c7], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@4e85dcb2]; rollback [true]
Hibernate: call next value for hibernate_sequence
Hibernate: call next value for hibernate_sequence
Disconnected from the target VM, address: '127.0.0.1:55458', transport: 'socket'
2020-02-24 15:16:38.447 INFO 16196 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@25ce9dc4 testClass = StudentRepositoryTest, testInstance = br.com.devdojo.awesome.StudentRepositoryTest@742ff096, testMethod = createWhenEmailIsNullShouldThrownConstraintViolationException@StudentRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@74ea2410 testClass = StudentRepositoryTest, locations = '{}', classes = '{class br.com.devdojo.awesome.ApplicationStart}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@17f62e33 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3eb738bb, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@185a6e9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@49438269, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@36807d48, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6f4a47c7], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]
java.lang.AssertionError: Expected test to throw (an instance of java.lang.IllegalStateException and exception with message a string containing "O campo nome do estudante é obrigatório")
at org.junit.Assert.fail(Assert.java:88)
at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
at org.junit.rules.ExpectedException.access$200(ExpectedException.java:106)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:245)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
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 org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
2020-02-24 15:16:38.461 INFO 16196 --- [ Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
Process finished with exit code -1
思路:
org.hibernate.validator.constraints.NotEmpty
注释现在已弃用(annotation type NotEmpty),我认为这是一个原因。尝试改用javax.validation.constraints.NotEmpty
注释。
以上内容就是爱站技术频道小编为大家分享的怎么用Spring数据测试ExpectedException-未引发异常,看完以上分享之后,大家应该都知道怎么用Spring数据测试ExpectedException-未引发异常了吧。