M
M
MaxLich2019-01-30 19:02:02
Java
MaxLich, 2019-01-30 19:02:02

Why does it give 404 when restoring?

Hello. There is a controller:

spoiler
**
 * REST-контроллер для непосредственной работы с активити
 */
@Controller
@RequestMapping(value = "/process", produces = {"application/json"})
public class ActivitiController {
    private static final Logger logger = LogManager.getLogger(ActivitiController.class);

    private final ActivitiService activitiService;

    @Autowired
    public ActivitiController(ActivitiService activitiService) {
        this.activitiService = activitiService;
    }

    /**
     * Стартует процесс в активити
     *
     * @param processName имя процесса, который нужно стартовать
     * @param params      параметры, передаваемые при старте процесса
     * @return идентификатор экземпляра процесса, созданного после старта процесса
     */
    @PostMapping(value = "/start")
    @ResponseBody
    public String startProcess(@RequestParam("processName") String processName, @RequestBody Map<String, String> params ) {
        Map<String, Object> variables = new HashMap<>();
        params.forEach(variables::put);

        ProcessInstance newProcessInstance = null;
        try {
            newProcessInstance = activitiService.startProcess(processName, variables);
        } catch (ActivitiServiceException e) {
            logger.warn(e);
            return "null";
        }
        return newProcessInstance.getProcessInstanceId();
    }
}

I want to test a method startProcess()in this class.
Wrote a unit test:
spoiler
@RunWith(SpringRunner.class)
@WebMvcTest(value = ActivitiController.class, secure = false)
public class ActivitiControllerTests {

    private static final String TEST_PROCESS_NAME = "process_name";
    private static final String TEST_PROCESS_INSTANCE_ID = "12";
    private static final String TEST_TASK_INSTANCE_ID = "14";

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ActivitiService activitiService;
    private ProcessInstance getTestProcessInstance() {
        return new ProcessInstance() {
            @Override
            public String getProcessInstanceId() {
                return TEST_PROCESS_INSTANCE_ID;
            }
       };
    }

    @Test
    public void testStartProcess() throws Exception {
        given(activitiService.startProcess(TEST_PROCESS_NAME, Collections.emptyMap()))
                .willReturn(getTestProcessInstance());

        mockMvc.perform(
                post("/process/start")
                        .param("processName", TEST_PROCESS_NAME)
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content("{\"key\":\"value\"}"))
                .andDo(print())
                .andExpect(status().isOk());
    }
}

After starting, it gives a response code 404, instead of the code 200.
Before that, there was another error (
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...)

), and for this I put an empty configuration one level up in the directory tree:
5c51cbe4ba0dd717144365.png
@SpringBootConfiguration
public class FakeConfig {}

This information is displayed in the console:
spoiler
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /process/start
       Parameters = {processName=[process_name]}
          Headers = {Content-Type=[application/json], Accept=[application/json]}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /process/start
       Parameters = {processName=[process_name]}
          Headers = {Content-Type=[application/json], Accept=[application/json]}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404
 <Click to see difference>

If I do, as in the example link , that is, I add a class to the level above:
@SpringBootApplication
public class DemoApplication {

    public static void main(String... args){
        SpringApplication.run(DemoApplication.class);
    }
}

then it outputs:
spoiler

MockHttpServletRequest:
HTTP Method = POST
Request URI = /process/start
Parameters = {processName=[process_name]}
Headers = {Content-Type=[application/json], Accept=[application/json]}
Body =
Session Attrs = {}
Handler:
Type = ru.cip.rlic.core.api.controller.rest.ActivitiController
Method = public java.lang.String ru.cip.rlic.core.api.controller.rest.ActivitiController.startProcess(java.lang.String,java.util.Map)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8], Content-Length=[4]}
Content type = application/json;charset=UTF-8
Body = null
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /process/start
Parameters = {processName=[process_name]}
Headers = {Content-Type=[application/json], Accept=[application/json]}
Body =
Session Attrs = {}
Handler:
Type = ru.cip.rlic.core.api.controller.rest.ActivitiController
Method = public java.lang.String ru.cip.rlic.core.api.controller.rest.ActivitiController.startProcess(java.lang.String,java.util.Map)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8], Content-Length=[4]}
Content type = application/json;charset=UTF-8
Body = null
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Response content
Expected :12
Actual :null

Adding DemoApplicationseems to help. But then it crashes on checking the return value. If you throw in the checked method any(), then everything passes. any()But I do n't know how to make it work without it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxLich, 2019-01-31
@MaxLich

The example from the article helped

D
Dmitry Eremin, 2019-01-31
@EreminD

you do post("/process/start")
And where is the /process part of the path declared ?
If done

@RestController
@RequestMapping("/process")
public class ActivitiController {

   @PostMapping(value = "/start")
   public String startProcess(@RequestParam("processName") String processName, @RequestBody Map<String, String> params ) {
        ...
    }
}

will work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question