resttemplate - 模拟 bean 无法在单元测试中注入依赖关系
问题描述
我想使用 TestRestemplate 测试我的 Spring Boot 应用程序,但是我无法测试获取 url,我在这里要做的是将一些预定义对象设置注入列表并模拟 find all 方法。
下面是我的测试代码的样子。
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class PersonControllerTests {
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private PersonRepository mockRepository;
@Before
public void init() {
List<Person> list = new ArrayList<>();
Person p1 = new Person("dumm1", "lastName1",22);
Person p2 = new Person("dumm2", "lastName2",32);
p1.setId(1l);
list.add(p2);
list.add(p1);
when(mockRepository.findAll()).thenReturn(list);
}
@Test
public void getPersonsGoodReq() throws Exception {
ResponseEntity<Person[]> response = restTemplate
.withBasicAuth("admin", "password")
.getForEntity("/persons/all", Person[].class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(response.getBody().length, 2);
}
}
我期望答案是 2,但是当我看到身体响应时,它是空数组。
可能出了什么问题我无法得到
解决方案
当您使用 JUnit Jupiter 时,您必须使用@BeforeEach
. @Before
来自 JUnit 4,因此没有作为测试生命周期的一部分被调用:
@BeforeEach
public void init() {
List<Person> list = new ArrayList<>();
Person p1 = new Person("dumm1", "lastName1",22);
Person p2 = new Person("dumm2", "lastName2",32);
p1.setId(1l);
list.add(p2);
list.add(p1);
when(mockRepository.findAll()).thenReturn(list);
}
推荐阅读
- javascript - 如何重新打开表单以使用 ReactJS 更新数据
- sqlite - Sqlite 和代号在模拟器上有效,但在我的手机上无效
- django - ImageField 未上传到指定目录
- javascript - 找到最大子数组的 Javascript 函数
- javascript - 检查函数回调中的重复
- pandas - 如何在 pandas DataFrame 的任何列中删除带有 NaN 的行
- python - 如果使用熊猫返回错误,如何删除数据
- python - Python:“StandardScaler”对象没有属性“_validate_data”
- javascript - 文本无法在 Bootstrap 导航栏切换中居中
- c++ - 模板类中静态成员的延迟初始化