Springboot mockMVC

本文详细记录了在SpringBoot项目中使用MockMVC和Mockito对RestTemplate进行打桩测试的过程。遇到的主要问题是RestTemplate.exchange方法的返回值匹配问题,以及如何正确配置WebApplicationContext。通过查阅资料和实践,最终解决了返回值为null pointer的问题,成功实现了对restTemplate.exchange的mock。文章还提到了Mockito的工作原理和一些常见错误的解决方案。
摘要由CSDN通过智能技术生成

需要对restTemplate.exchange(设备侧)打mock,而不是对service层上的controller打mock,

对数据库等中间件都要打桩,所以要用到@Profile分离配置,详见上一篇:

https://blog.csdn.net/jass535/article/details/109461642

mock的一般用法:https://blog.csdn.net/wo541075754/article/details/88983708

mock本身不难,但是对resttemplate打桩就有点麻烦了:

https://stackoverflow.com/questions/42406625/how-to-mock-resttemplate-in-java-spring

@RunWith(MockitoJUnitRunner.class) 
public class ServiceTest {
    @Mock
    RestTemplate restTemplate;
    @InjectMocks
    @Spy
    Service service;
    ResponseEntity responseEntity = mock(ResponseEntity.class);
    //事实证明,我们用的return值是个具体的Entity,而不是mock出来的,所以不能这么写

    @Test
    public void test() throws Exception {
        Mockito.when(restTemplate.getForEntity(
                Mockito.anyString(),
                ArgumentMatchers.any(Class.class)
                ))
                .thenReturn(responseEntity);
        boolean res = service.isEnabled("something");
        Assert.assertEquals(res, false);
    }

遇到的坑就是代码里注释的那一句,根据这篇文章,判断给的return应该是个实体ResponseEntity: 

https://www.baeldung.com/spring-mock-rest-template

    @Test
    public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() {
        Employee emp = new Employee(“E001”, "Eric Simmons"); 
        //就是从这句得到的灵感

        Mockito
          .when(restTemplate.getForEntity(
            “http://localhost:8080/employee/E001”, Employee.class))
          .thenReturn(new ResponseEntity(emp, HttpStatus.OK));
 
        Employee employee = empService.getEmployee(id);
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值