在编写控制器类的单元测试用例时,我模拟了服务层调用以返回所需的值,但是,它返回了null。
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest {
@Mock
private Service serviceMock;
@InjectMocks
private Controller controller;
private MockMvc mockMvc;
/**
* Sets the up.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc =
MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void method1() throws Exception {
when(this.serviceMock.associateTag(any(Request.class), null))
.thenReturn(Responses.SUCCESS);
mockMvc.perform(post("/tag/assign").contentType(MediaType.APPLICATION_JSON).content(request)) .andExpect(MockMvcResultMatchers.status().isOk());
}
@PostMapping("/assign")
public RestResponse assignTag(@RequestBody final TagAssociation
tagAssociation) {
final TagResponses serviceResponse =
this.service.associateTag(tagOrderAssociation, null);
serviceResponse始终为null,我期望枚举响应Responses.SUCCESS
testException = org.springframework.web.util.NestedServletException:请求处理失败;嵌套的异常是java.lang.NullPointerException
服务层具有许多自动关联的依赖项。 我还需要模拟吗? 无法找出失败的确切原因。
答案 0 :(得分:1)
在存根时使用匹配器时,必须将其用于所有输入参数。因此,尝试:
when(this.serviceMock.associateTag(Mockito.any(Request.class), Mockito.eq(null)))
如果您想进一步阅读,那么我在Mockito Stubbing
上写了这篇文章。