【问题标题】:mock bean unable to inject dependecy in unit testmockbean 无法在单元测试中注入依赖项
【发布时间】:2021-05-17 12:06:36
【问题描述】:

我想使用 TestRestemplate 测试我的 Spring Boot 应用程序,但是我无法测试 get 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,但是当我看到正文响应时,它是空数组。

可能出了什么问题我无法理解

【问题讨论】:

  • 你能把这个测试类的import部分添加到你的问题中吗?
  • @rieckpil 添加了
  • 不确定这是否是此问题的根本原因,但您将 JUnit 4 与 JUnit 5 混合使用。org.junit.jupiter.api.Test 是 JUnit Jupiter(Junit 5 的一部分),其余的是 JUnit 4。是您的打算使用 4 还是 5?
  • 它是 Junit 5 Jupiter

标签: resttemplate spring-boot-test spring-resttemplate


【解决方案1】:

当您使用 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);
    
}

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2021-06-19
    • 1970-01-01
    • 2018-01-11
    • 2017-04-01
    • 1970-01-01
    • 2016-07-12
    相关资源
    最近更新 更多