【发布时间】:2017-06-22 07:29:37
【问题描述】:
我正在使用 Mockito 来模拟春豆。
当我模拟一个界面时它工作正常。
在我们的应用程序中,很少有没有实现任何接口的@Component bean。
当我尝试模拟此类组件时,spring 上下文会尝试将属性注入这些组件中。
Mockito 不支持模拟不实现任何接口的 spring 组件吗?
根据要求附上示例
public interface EmployeeInterface {
public Long saveEmployee(Employee employee);
}
@Component
public class EmployeeImpl implements EmployeeInterface {
@Autowired
public EmailSender emailSender
public Long saveEmployee(Employee employee) {
...
}
}
public interface EmailSender {
public boolean sendEmail(Email email);
}
@Component
public class EmailSenderImpl implements EmailSender {
@Autowired
MailServerInfo MailServerInfo;
public boolean sendEmail(Email email) {
...
}
}
public interface MailServerInfo {
public String getMailServerDetails();
}
@Component
public class MailServerInfoImpl {
public String getMailServerDetails() {
...
}
}
@Profile("Security-test")
@Configuration
public class SecurityTestMockConfiguration {
@Bean
@Primary
public EmailSender emailSender() {
return Mockito.mock(EmailSender.class);
}
}
@ActiveProfiles("Security-test")
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context-test.xml" })
public class MyTest {
@Autowired
EmployeeInterface employeeInterface;
@Test
public void testSaveEmployee() {
employeeInterface.saveEmployee(employee);
}
}
在上面的示例中,如果我使用 Mockito 模拟 EmailSender,它可以正常工作。
在下面的场景中,EmailSender 是一个没有实现任何接口的 Spring 组件。在以下情况下,我在自动接线时出错。
public interface EmployeeInterface {
public Long saveEmployee(Employee employee);
}
@Component
public class EmployeeImpl implements EmployeeInterface {
@Autowired
public EmailSender emailSender
public Long saveEmployee(Employee employee) {
...
}
}
@Component
public class EmailSender {
@Autowired
MailServerInfo MailServerInfo;
public boolean sendEmail(Email email) {
...
}
}
public interface MailServerInfo {
public String getMailServerDetails();
}
@Component
public class MailServerInfoImpl {
public String getMailServerDetails() {
...
}
}
@Profile("Security-test")
@Configuration
public class SecurityTestMockConfiguration {
@Bean
@Primary
public EmailSender emailSender() {
return Mockito.mock(EmailSender.class);
}
}
@ActiveProfiles("Security-test")
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context-test.xml" })
public class MyTest {
@Autowired
EmployeeInterface employeeInterface;
@Test
public void testSaveEmployee() {
employeeInterface.saveEmployee(employee);
}
}
在第二种情况下,自动装配失败,因为 EmailSender 找不到 MailServerInfo 实现。
【问题讨论】:
-
请附上你的测试课
-
附上测试课
-
请提供 context-test.xml。
-
您为什么使用 PowerMock 的
PowerMockRunner和 Mockito 的mock?你应该坚持使用一个模拟库。 -
我使用 PowerMockRunner 在我的测试中模拟了一个静态类
标签: mocking mockito powermock spring-test powermockito