【问题标题】:How to mock any services inside a @MockedBean?如何模拟@MockedBean 中的任何服务?
【发布时间】: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


【解决方案1】:

就我而言,注入模拟的最佳方法是使用MockitoJUnitRunner

@RunWith(MockitoJUnitRunner.class)
public class MocksTests {

    @InjectMocks
    private ParentService parent;

    @Mock
    private InnerService inner; // this will be injected into parent

    //your tests

}

【讨论】:

  • 好吧,但我想在spring-boot-test 的上下文中运行,因此必须使用SpringJUnit4ClassRunner.class
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多