gpt4 book ai didi

spring - 如何模拟 Spring Data 和单元测试服务

转载 作者:行者123 更新时间:2023-12-05 00:55:18 25 4
gpt4 key购买 nike

我正在尝试对服务方法进行单元测试。服务方法调用 spring 数据存储库方法来获取一些数据。我想模拟那个存储库调用,并自己提供数据。怎么做?关注 Spring Boot documentation ,当我模拟存储库并在我的测试代码中直接调用存储库方法时,模拟正在工作。但是当我调用 service 方法时,它又会调用存储库方法,mocking 不起作用。下面是示例代码:

服务等级:

@Service
public class PersonService {

private final PersonRepository personRepository;

@Autowired
public PersonService(personRepository personRepository) {

this.personRepository = personRepository;
}

public List<Person> findByName(String name) {
return personRepository.findByName(name); // I'd like to mock this call
}
}

测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

// http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans
@MockBean
private PersonRepository personRepository;

@Autowired
private PersonService personService;

private List<Person> people = new ArrayList<>();

@Test
public void contextLoads() throws Exception {

people.add(new Person());
people.add(new Person());

given(this.personRepository.findByName("Sanjay Patel")).willReturn(people);

assertTrue(personService.findByName("Sanjay Patel") == 2); // fails
}
}

最佳答案

对于 Spring Data 存储库,您需要指定 bean 名称。通过类型模拟似乎不起作用,因为存储库是运行时的动态代理。
PersonRepository 的默认 bean 名称是“personRepository”,所以这应该有效:

@MockBean("personRepository")
private PersonRepository personRepository;

这是完整的测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

// http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans
@MockBean("personRepository")
private PersonRepository personRepository;

@Autowired
private PersonService personService;

private List<Person> people = new ArrayList<>();

@Test
public void contextLoads() throws Exception {

people.add(new Person());
people.add(new Person());

given(this.personRepository.findByName("Sanjay Patel")).willReturn(people);

assertTrue(personService.findByName("Sanjay Patel") == 2); // fails
}
}

关于spring - 如何模拟 Spring Data 和单元测试服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38294068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com