我想测试控制器方法是否返回http status 200
package pl.azimuthit.flightmap.service.module.route.util.alert;
...
@Slf4j
@Controller
public class FlightAcknowledgeAlertsServiceImpl implements FlightAcknowledgeAlertsService {
...
@Override
@RequestMapping(value = SERVICE_MAPPING, method = POST)
public @ResponseBody
ResponseEntity acknowledgeAlert(@PathVariable(ALERT_ID) String alertId) {
....
try {
Map.Entry<AlertID, AlertJTO> entry = alertsCache.findUserEntryById(alertId, userLogin);
...
return new ResponseEntity(HttpStatus.OK);
} catch (Exception ex) {
...
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
我模拟了alertCache并添加了when()
,它设置了findUserEntryById
以返回给定的条目。不幸的是,它返回一个null,不知道为什么,这将在以后抛出null并捕获“捕获”。问题是,尽管设置了应返回的内容,为什么它仍返回null。
结果是http代码400,而不是200。无论传递什么,我都希望正确传递所有内容。
public Map.Entry<AlertID, AlertJTO> findUserEntryById(String alertId, String userLogin) {
return alertJTOCache.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 FlightAcknowledgeAlertsServiceImplTest {
private static final String ALERT_ID = "123";
...
private MockMvc mockMvc;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webContext)
.build();
}
...
@Test
public void testAcknowledgeOfExistingAlert() 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(alertsCache.findUserEntryById(any(),any())).thenReturn(entry);
//then
mockMvc.perform(MockMvcRequestBuilders.post(url(), ALERT_ID)
.param(FlightAcknowledgeAlertsService.ALERT_ID, ALERT_ID))
.andExpect(MockMvcResultMatchers.status()
.isOk());
}
答案 0 :(得分:0)
我认为你失踪了
@InjectMocks
FlightAcknowledgeAlertsServiceImpl controllerUnderTest;
所以控制器实例不会得到模拟。
答案 1 :(得分:0)
看看Spring的someone@AMacBookPro | SSW810GradingScript | master via GradingScript
» python3 -m src.HW02
Current absolute path: /Users/benjamin/Documents/Python_Scripts/SSW810GradingScript/src/HW02/submissions
__file__: /Users/benjamin/Documents/Python_Scripts/SSW810GradingScript/src/HW02/submissions/__init__.py | __name__: src.HW02.submissions | __package__: src.HW02.submissions
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/benjamin/Documents/Python_Scripts/SSW810GradingScript/src/HW02/__main__.py", line 4, in <module>
from . import submissions
File "/Users/benjamin/Documents/Python_Scripts/SSW810GradingScript/src/HW02/submissions/__init__.py", line 24, in <module>
SUBMITTED_HOMEWORK = import_python_files()
File "/Users/benjamin/Documents/Python_Scripts/SSW810GradingScript/src/HW02/submissions/__init__.py", line 20, in import_python_files
imported_modules.append(importlib.import_module(file_name[:-3]))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'HW02_YinghuiCai'
批注。删除public static void forceToJSONArray(JSONObject xmlJSONObj, String obj) throws org.json.JSONException
{
// where "JSONObject xmlJSONObj" is my JSONObject obtained by passing the XML throug the metod toJSONObject
// and where "String obj" is the name of the JSONObject I want to force to JSONArray
Object myObj = xmlJSONObj.opt(obj);
if (myObj == null)
{
// if my obj doesn't exist inside my xmlJSONObj i create it empty
JSONArray jsonArray = new JSONArray();
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof JSONObject )
{
// if exist but is a JSONObject, I force it to JSONArray
JSONObject myJSONObj = (JSONObject)myObj;
JSONArray jsonArray = new JSONArray();
jsonArray.put(myJSONObj);
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof String || myObj instanceof Integer )
{
// if exist but is a primitive entry (like in your case), I force it to a "primitive" JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray.put(myObj);
xmlJSONObj.put(obj, jsonArray);
}
}
并仅留下:
@MockBean
然后执行正常的when / thenReturn事情。