java - 使用mockito和spring mock的authowired bean的Mock方法

标签 java spring-boot unit-testing

我必须对包含两个方法 method1 和 method2 的 MyService 进行测试:

并且 method1 调用 method2 (method1 --> method2 )

所以我的测试类中有这样的东西

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootApplicationTest.class)
@ContextConfiguration(classes = { conf.class })
public class CommonCAMServiceTest {

    @Autowired
    private MyService myService;

     test_method_1(){...}// this is what i want to implement and i have to mock the method2 call
     test_method_2(){...}//this work fine


... 

所以我想测试我的方法1,但是使用方法的模拟(甚至我的服务类是 Autowiring 的而不是模拟的)

谢谢

最佳答案

Mockito 支持我所说的“部分模拟”; 它被称为 spy 。

无需为您的服务创建模拟 bean, 创建一个 spy 。 还, 正如其他答案中提到的, 不要使用 @Autowire 来使用该服务。

这里是一些示例代码:

public class CommonCAMServiceTest
{
    @Spy
    private MyService myService;

    @Before
    public void before()
    {
        MockitoAnnotations.initMocks(this);

        // Mock method2 for every test.
        doReturn(something).when(myService).method2();
    }

    @Test
    public void someTestName()
    {
        // Mock method2 in this test.
        doReturn(somethingElse).when(myService).method2();

        ... call method1 to do stuff.
    }
}

关于java - 使用mockito和spring mock的authowired bean的Mock方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862424/

相关文章:

java - 液位动画(电池医生)

spring-boot:自动配置事务管理器

c# - 如何对需要从硬盘加载数据的算法进行单元测试(在本例中为图片!)?

c# - 单元测试方法的有效输入

javascript - 无法对通过 Controller 发生的 http 调用进行单元测试

Java 扫描器字符串输入 If 语句不起作用

java - 在每个标点符号之间插入空格

java - Spring WS 客户端发送 HTTPS 请求

spring-boot - 事务发件箱模式与微服务中的 ChainedKafkaTransactionManager

spring - 是否可以使用在 Windows IIS 上运行的嵌入式 Tomcat Web 服务器从 Spring Boot 应用程序的 URL 中删除端口?