【发布时间】:2021-02-05 09:41:55
【问题描述】:
我正在使用 Java 单元测试。当我们正确地给出参数时,单元测试应该没有任何错误(绿色)。但是我遇到了这样的错误。 Java 1.8 版
Expecting code to raise a throwable.
井字游戏服务
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");
}
}
井字游戏
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 {
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'
}
有什么问题?请帮帮我
【问题讨论】:
标签: spring-boot unit-testing junit