java - 尽管有`when()`方法它返回null
问题描述
我想测试控制器方法是否返回http status 200
@Slf4j
@Controller
public class AcknowledgeAlertsServiceImpl implements AcknowledgeAlertsService {
...
@Override
@RequestMapping(value = SERVICE_MAPPING, method = POST)
public @ResponseBody
ResponseEntity acknowledge(@PathVariable(ALERT_ID) String alertId) {
....
try {
Map.Entry<AlertID, AlertJTO> entry = cache.findUserEntryById(alertId, userLogin);
...
return new ResponseEntity(HttpStatus.OK);
} catch (Exception ex) {
...
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
我已经模拟了缓存并添加了when()
哪个集合findUserEntryById
来返回给定的条目。不幸的是,它返回一个空值,不知道为什么,稍后会抛出空值并捕获“捕获”。问题是为什么它返回 null 尽管设置了它应该返回的行为。结果是 http 代码 400,而不是 200。我想正确传递所有内容,无论传递什么。
public Map.Entry<AlertID, AlertJTO> findUserEntryById(String alertId, String userLogin) {
return cache.entrySet()
.stream()
.filter(key -> key.getKey()
.getUserLogin()
.equals(userLogin))
.filter(entry -> entry.getValue()
.getId()
.equals(alertId))
.findFirst()
.orElse(null);
}
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "..." })
@WebAppConfiguration
public class AcknowledgeAlertsServiceImplTest {
private static final String ALERT_ID = "123";
...
private MockMvc mockMvc;
...
...
@Test
public void acknowledgeOfExistingAlert() throws Exception {
//given
UserData userData = mock(UserData.class);
AlertID alertID = mock(AlertID.class);
AlertJTO alertJTO = mock(AlertJTO.class);
Map.Entry<AlertID, AlertJTO> entry = new AbstractMap.SimpleEntry<>(alertID, alertJTO);
//when
when(flightmapUserContext.getUserData()).thenReturn(userData);
when(cache.findUserEntryById(any(),any())).thenReturn(entry);
//then
mockMvc.perform(MockMvcRequestBuilders.post(url(), ALERT_ID)
.param(AcknowledgeAlertsService.ALERT_ID, ALERT_ID))
.andExpect(MockMvcResultMatchers.status()
.isOk());
}
解决方案
看看 Spring 的@MockBean
注解。删除@InjectMocks
并离开:
@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerIT {
@MockBean
private AlertsCache alertsCache;
@Autowired
private MockMvc mockMvc;
@Before
public void setUp() {
when(alertsCache.findUserById(anyLong())).thenReturn(someEntry);
}
}
并做正常的 when/thenReturn 事情。
推荐阅读
- c# - 向班级发送 Restsharp 响应
- python - 从字符串路径列表构建树结构
- ruby-on-rails - 如何获取关联模型的最后一条记录以防止 N+1 查询?
- next.js - 如何仅允许通过下一个 js 中的语言环境子路径访问页面
- android - imageCapture.takePicture - 保存的图像转换为位图
- format - 在 fortran 中没有换行符和多次写入的格式说明符
- node.js - 我可以告诉 babel 替换输出目录吗?
- python - 更改子类的返回类型
- r - data.table:用 keyby 对 j 中的分组变量进行子集化
- docker - 如何在 Windows 命令提示符中设置环境变量,以便在 `docker run -e FOO -e ...` 中传递它们,就像使用 bash 导出一样