在Spring Boot中模拟 [英] Mocking in Spring Boot

查看:136
本文介绍了在Spring Boot中模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎以及作为可执行JAR文件的程序包生成了Spring Boot Web应用程序.

I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

使用的技术:

Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat嵌入8.5.6,Maven 3,Java 8

Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8

我有这些课程:

package com.tdk.helper;


@Component
public class BookMessageDecoder implements MessageDecoder {

    private String messageData;



    public BookMessageDecoder() {
        super();
    }


    /**
     * @param data4
     */
    public BookMessageDecoder(String messageData) {
        this.messageData=messageData;
    }
..
}

@RestController
public class BookCallBackController {


    BookSystemManager bookSystemManager;

    @Autowired
    BookMessageDecoder messageDecoder;

    @Autowired  
    public BookCallBackController(BookSystemManager bookSystemManager) {
        this.bookSystemManager = bookSystemManager;
    }

..
}


@RunWith(SpringRunner.class)
public class BookCallBackControllerTests {

    @MockBean
    BookMessageDecoder messageDecoder;


    private BookCallBackController controller;

    @Before
    public void setUp() throws Exception {

         given(this.messageDecoder.hasAlarm()).willReturn(false);

         controller = new BookCallBackController(new StubBookSystemManager());

    }
..
}

即使我在嘲笑bean bookMes​​sageDecoder,使用它时也为null!

Even I am mocking the bean bookMessageDecoder, is null when I use it !

推荐答案

对于控制器测试,您始终可以使用springs @WebMvcTest(BookCallBackController.class)批注. 另外,您还需要为对控制器的模拟Http请求配置一个mockMvc. 在那之后,您可以自动装配mockMvc @Autowired MockMvc mockMvc; 现在您可以模拟对控制器@MockBean BookMessageDecoder messageDecoder;

For Controller test you can always use springs @WebMvcTest(BookCallBackController.class) annotations. Also you need to configure a mockMvc for mock Http request to your controller. After that you can autowire mockMvc @Autowired MockMvc mockMvc; Now you can mock you dependency to controller @MockBean BookMessageDecoder messageDecoder;

@RunWith(SpringRunner.class)
@WebMvcTest(BookCallBackController.class)
@AutoConfigureMockMvc
public class BookCallBackControllerTests {

    @MockBean
    BookMessageDecoder messageDecoder;

    @Autowired 
    MockMvc mockMvc; 

    @Before
    public void setUp() throws Exception {

         given(this.messageDecoder.hasAlarm()).willReturn(false);

    }


..
}

这篇关于在Spring Boot中模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆