Mocking in Spring Boot

自闭症网瘾萝莉.ら 提交于 2019-12-12 02:18:14

问题


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

Technologies used:

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

I have these classes:

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());

    }
..
}

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


回答1:


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);

    }


..
}


来源:https://stackoverflow.com/questions/42701638/mocking-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!