我正在使用Mockito模擬彈簧豆。模擬彈簧組件
它可以正常工作,當我嘲笑一個接口。
在我們的應用程序中,很少有@Component bean沒有實現任何接口。
當我嘗試模擬這樣的組件時,spring上下文嘗試在這些組件內注入屬性。
Mockito不支持不實現任何接口的模擬彈簧組件嗎?
附例的要求
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執行失敗。
請附上您的測試類 –
附上測試類 – lives
請提供context-test.xml。 –