【发布时间】:2016-09-13 09:47:08
【问题描述】:
是否可以在 MockedBean 中忽略/模拟任何注入的依赖项?
例子:
@Service
public class MyService {
@Autowired
private MailerService mailer;
public void test1() {
//does not use mailer
}
public void test2() {
//...
mailer.send();
}
}
@Service
public class MailerService {
//I want these to be automatically mocked without explicit declaration
@Autowired
private JavaMailSender sender;
@Autowired
private SomeMoreService more;
//also these should be mocked without having to provide properties
@Value("${host}") private String host;
@Value("${user}") private String user;
@Value("${pass}") private String pass;
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyServiceTest {
@Autowird
private MyService myservice;
@MockBean
private MailserService mailer;
@Test
public void test1() {
myservice.test1();
}
}
我可以使用@MockBean 来解决邮件注入依赖。但是,任何在模拟 bean 内的服务也必须被显式模拟。
问题:是否可以“远离”模拟服务。意思是,只模拟 bean,而不关心 @MockedBean 里面的内容(或者自动模拟 @MockedBean 里面的任何内容)?
【问题讨论】:
-
我不知道。对接口进行编程将是最简单的解决方案。
mailerService仍然是一个弹簧管理的 bean(尽管是一个模拟)。所以它仍在处理中,因为它是一个类,注释仍在处理中。
标签: java spring junit spring-boot mockito