j.x*_*ero 1 unit-testing controller spring-boot
根据教程测试 Web 层,可以使用以下代码测试控制器是否已创建:
@Test
public void contexLoads() throws Exception {
assertThat(controller).isNotNull();
}
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (HomeController)"
Run Code Online (Sandbox Code Playgroud)
即使声明:
import static org.junit.Assert.assertThat;
Run Code Online (Sandbox Code Playgroud)
我的类的代码与示例中给出的代码相同:
package com.my_org.my_app;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SmokeTest {
@Autowired
private HomeController controller;
@Test
public void contexLoads() throws Exception {
assertThat(controller).isNotNull();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将断言语句更改为:
@Test
public void contexLoads() throws Exception {
assertNotNull(controller);
}
Run Code Online (Sandbox Code Playgroud)
它按预期工作。
我的控制器类有一些 Autowired 对象,但由于它们是由 Spring Boot 管理的,所以应该不是问题。知道有什么问题assertThat(controller).isNotNull();吗?提前致谢。
小智 5
您使用了错误的assertThat导入。您应该使用以下内容:
import static org.assertj.core.api.Assertions.assertThat;
Run Code Online (Sandbox Code Playgroud)
正确的方法位于 AssertJ 库中,而不是在 JUnit 中。
| 归档时间: |
|
| 查看次数: |
947 次 |
| 最近记录: |