在 Spring 5.0.7.RELEASE 中模拟服务
Mocking a service in Spring 5.0.7.RELEASE
我有一个 Spring 5.0.7.RELEASE 应用程序,有一些 WebLayer 测试 我在我的应用程序中有这个测试:
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class HongoControllerTest {
@Mock
FactureService factureService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
ObjectMapper obj = new ObjectMapper();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
when(factureService.setLockFilter(any())).thenReturn(Boolean.TRUE);
}
}
但是当我 运行 测试时,FactureService 没有被模拟
我不太确定,因为你没有展示实际测试,但我想你应该使用 @MockBean
而不是 @Mock
。
当您自己进行依赖注入时,@Mock
用于普通单元测试。
@MockBean
当您想将 Mock 用作常规 Bean 时用于集成测试。
长话短说。试试这个:
@MockBean
FactureService factureService;
有关详细信息,请查看此 article。
我有一个 Spring 5.0.7.RELEASE 应用程序,有一些 WebLayer 测试 我在我的应用程序中有这个测试:
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class HongoControllerTest {
@Mock
FactureService factureService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
ObjectMapper obj = new ObjectMapper();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
when(factureService.setLockFilter(any())).thenReturn(Boolean.TRUE);
}
}
但是当我 运行 测试时,FactureService 没有被模拟
我不太确定,因为你没有展示实际测试,但我想你应该使用 @MockBean
而不是 @Mock
。
@Mock
用于普通单元测试。
@MockBean
当您想将 Mock 用作常规 Bean 时用于集成测试。
长话短说。试试这个:
@MockBean
FactureService factureService;
有关详细信息,请查看此 article。