Alexei
Alexei

Reputation: 15646

Spring Boot 2 can't find @Test(expected = xxx)

java 1.8

In my Spring Boot 2 project:

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()
}

In my test:

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());
    }
}

Test myTest() success work, but I get compile error in test shouldNotAllowToPersistNullProperies():

 error: cannot find symbol
    @Test(expected = javax.validation.ConstraintViolationException.class)
          ^
  symbol:   method expected()
  location: @interface Test

Upvotes: 0

Views: 2268

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36103

You could go with JUnit 5 instead of JUnit 4.

Remove:

testImplementation 'junit:junit:4.4'

JUnit 5 does not know "expected" instead us it like this with assertThrows:

@Test
public void shouldNotAllowToPersistNullProperies() {

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

}

Upvotes: 1

Related Questions