java mock什么意思_java @Mock, @MockBean 与 Mockito.mock( ) 之间的差异

纯Mockito库import org.mockito.Mock;

...

@Mock

MyService myservice;

和import org.mockito.Mockito;

...

MyService myservice = Mockito.mock(MyService.class);

来自Mockito库,在功能上是等价的,

它们允许模拟类或接口,并记录和验证行为。

@Before

public void initMocks() {

MockitoAnnotations.initMocks(this);

}

启用Mockito注释的另一种方法是使用@RunWith来注释测试类,方法是指定执行此任务的MockitoJUnitRunner以及其他有用的东西:@RunWith(org.mockito.runners.MockitoJUnitRunner.class)

public MyClassTest{...}

Spring Boot库包装Mockito库

这是一个Spring Boot类:import org.springframework.boot.test.mock.mockito.MockBean;

...

@MockBean

MyService myservice;

类包含在spring-boot-test库中。

它允许在spring ApplicationContext中添加Mockito mocks,

通常,@WebMvcTest将仅限于一个控制器,并且与@MockBean一起使用,为所需的协作者提供模拟实现。

以下是一个示例:import org.junit.Test;

import org.junit.runner.RunWith;

import org.mockito.Mockito;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

import org.springframework.boot.test.mock.mockito.MockBean;

import org.springframework.http.MediaType;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)

@WebMvcTest(FooController.class)

public class FooControllerTest {

@Autowired

private MockMvc mvc;

@MockBean

private FooService fooServiceMock;

@Test

public void testExample() throws Exception {

Foo mockedFoo = new Foo("one","two");

Mockito.when(fooServiceMock.get(1))

.thenReturn(mockedFoo);

mvc.perform(get("foos/1")

.accept(MediaType.TEXT_PLAIN))

.andExpect(status().isOk())

.andExpect(content().string("one two"));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值