gpt4 book ai didi

java - 当我们使用 Spring Autowiring DAO 时,如何在我的单元测试中模拟出各种结果集?

转载 作者:行者123 更新时间:2023-11-29 03:55:30 24 4
gpt4 key购买 nike

假设我有一个看起来像这样的经理:

public class CustomerManager {

@Autowired
@Qualifier("customerDAO")
private CustomerDAO customerDAO;

public List<Customer> findCustomers() {

List<Customer> customers = customerDAO.findCustomers();
if (customers.size() == 0) {
// Do something else...
}
if (customers.size() == 1) {
// Do something else...
}

return customers;
}
}

现在是我的测试配置示例:

public class CustomerManagerUnitTest extends AbstractDependencyInjectionSpringContextTests {

protected String[] getConfigLocations() {
return new String[] { "classpath:test-spring-customer.xml" };
}

public void testFindCustomers_NoResults() {

CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();

// Test...
}

public void testFindCustomers_OneResult() {

CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();

// Test...
}

public void testFindCustomers_MultipleResults() {

CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();

// Test...
}
}

根据客户数量(或客户数据类型),我需要做一些具体的事情。我正在使用 Spring 的 AbstractDependencyInjectionSpringContextTests 来使用测试上下文。因此,从测试上下文配置中获取模拟 DAO,并 Autowiring 它是没有问题的。但是,这意味着对于需要测试不同结果集的每个测试,我都需要有不同的上下文配置和不同的模拟 DAO。现在您可以看到我的模拟 DAO 只有一个测试配置。处理此问题的最佳方法是什么?

最佳答案

不要让 Spring 创建您的 CustomerManager 进行测试。手动创建它并手动注入(inject)模拟 DAO。这就是依赖注入(inject)的全部要点:

public class CustomerManager {

private CustomerDAO customerDAO;

@Autowired
public CustomerManager(@Qualifier("customerDAO") CustomerDAO customerDAO) {
this.customerDAO = customerDAO;
}
}

public class CustomerManagerUnitTest {

public void testFindCustomers_OneResult() {
CustomerDAO mockCustomerDAO = ...;
CustomerManager customerManager = new CustomerManager(mockCustomerDAO);

expect(customerDAO.findCustomers()).andReturn(...);
// ...
List<Customer> customers = customerManager.findCustomers();

// Test...
}
}

关于java - 当我们使用 Spring Autowiring DAO 时,如何在我的单元测试中模拟出各种结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6612689/

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