I have a spring controller which has outter environment dependency in the requesting mapping method and the dependency was intruduced by a factory single-instance method:
@RequestMapping(path = "/video_course", method = RequestMethod.POST)
public JSONObject createVideoCourse(@RequestBody @Valid VideoCourseDTO dto,
HttpServletRequest request) {
try {
ContextManagerFactory.getInstance().setContext(request); // How to mock the ContextManagerFactory in unit testing?
Context ctx = ContextManagerFactory.getInstance().getContext();
Course course = ctx.getCourse();
Content parentContent = ctx.getContent();
long id = videoCourseService.addVideoCourse(dto.title, dto.available,
String.join(",", dto.keywords), dto.videos, course, parentContent, dto.tracking);
JSONObject json = new JSONObject();
json.put("vc_id", id);
return json;
} catch (Exception e) {
logger.error("createVideoCourse", e);
throw new ServerInternalException(e.getMessage());
}
}
With the following junit test case:
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {SpringMvcTestConfig.class, HibernateDevConfig.class,
BlackboardEnvironmentConfig.class, VideoRepoTestConfig.class, VideoCourseTestConfig.class})
@Sql("classpath:video_course.sql")
@Transactional
@ActiveProfiles("dev")
public class VideoCourseApiTest {
private static Logger logger = LoggerFactory.getLogger(VideoCourseApiTest.class);
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testCreateVideoCourse() throws Exception {
JSONObject json = new JSONObject();
// construct the request body json string ...
logger.debug("request body: \n{}",json.toJSONString());
mockMvc
.perform(post("/course/video_course").content(json.toJSONString())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("vc_id", is(greaterThan(0))));
}
}
And I don't know how to mock the ContextManagerFactory with Mockito in such situation. Anyone could help me? Thanks.
Aucun commentaire:
Enregistrer un commentaire