Issue
I am using Java unit tests. When we give the parameters correctly, the unit test should work without any errors (green). But I am getting such an error. Java version 1.8
Expecting code to raise a throwable.
TicTacToeService
public class TicTacToeService {
public void play(int x, int y) {
if(x<0)
throw new IllegalArgumentException("x cannot be negative");
if (y < 0)
throw new IllegalArgumentException("y cannot be negative");
if (x > 2)
throw new IllegalArgumentException("x cannot be greater than 2");
if (y > 2)
throw new IllegalArgumentException("y cannot be greater than 2");
}
}
TicTacToeTest
public class TicTacToeTest {
private TicTacToeService ticTacToeService = new TicTacToeService();
@Test
public void givenXIsNegativeExpectException(){
int x = -1;
int y = 1;
Assertions.assertThatThrownBy(() -> ticTacToeService.play(x, y))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("X cannot be negative");
}
@Test
public void givenYIsNegativeExpectException(){
int x = 1;
int y = -1;
Assertions.assertThatThrownBy(() -> ticTacToeService.play(x, y))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("y cannot be negative");
}
}
dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation("org.modelmapper:modelmapper:2.3.7")
implementation 'org.springframework.boot:spring-boot-starter-validation'
testCompile group: 'junit', name: 'junit', version: '4.4'
implementation 'org.liquibase:liquibase-core'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testCompile group: 'org.assertj', name: 'assertj-core', version: '3.6.1'
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.7.0'
}
What is the problem? please help me
Solution
I suspect that you are using assertThatThrownBy
but in reality, you want to use assertThrows
. You can check this link for example.
Answered By - Léo Schneider