首页 > 解决方案 > 在名称为 '' 的 DispatcherServlet 中找不到具有 URI [/api/transactions] 的 HTTP 请求的映射

问题描述

我以为这是标准配置。但我得到了 404 回复。我还应该在哪里配置 Spring Boot ?

@RestController
@RequestMapping("/api")
public class TransactionStatisticsController {

    public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);

    @RequestMapping(value = "/transactions",
                    method = RequestMethod.POST)
    public ResponseEntity sendTransaction(@RequestBody Transaction request) {
        logger.info( request.toString());
        return new ResponseEntity(HttpStatus.OK);
    }

}

这是我的测试。

@JsonTest
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class TransactionStatisticsRestTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private JacksonTester<Transaction> json;

    private static Transaction transaction;

    @BeforeClass
    public static void createTransaction(){
        BigDecimal amount = new BigDecimal(12.3343);
        transaction = new Transaction(amount.toString(),
                                      "2010-10-02T12:23:23Z");
    }

    @Test
    public void getTransactionStatus() throws Exception {

        final String transactionJson = json.write(transaction).getJson();
        mockMvc
                .perform(post("/api/transactions")
                .content(transactionJson)
                .contentType(APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());
    }

    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsBytes(transaction);
    }
}

提出的要求是

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/transactions
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}
             Body = {"amount":"12.3343000000000007077005648170597851276397705078125","timestamp":"2010-10-02T12:23:23Z[UTC]"}
    Session Attrs = {}

Handler:
             Type = null

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 = []

更新:我添加了一个指向基础包的组件扫描。我现在看不到那个错误。请查看有答案的评论。

标签: spring-mvcspring-boot

解决方案


似乎 using@JsonTest甚至不允许加载 Application Context,未加载结果映射并且它的 throw 404 所以@JsonTest不是替代品@SpringBootTest,它是一种轻松测试的方法json serialization/de-serialization

根据文档:

您可以使用 @JsonTest 注释。@JsonTest 自动配置可用的支持 JSON 映射器,它可以是以下库之一:

  1. Jackson ObjectMapper、任何@JsonComponent bean 和任何Jackson 模块
  2. 格森
  3. 乔布斯

如果通过使用 Gson 并删除@JsonTest您的测试运行良好..(在 pom 中添加 Gson 依赖项)

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class DemoKj01ApplicationTests {

    @Autowired
    private MockMvc mockMvc;

    private static Transaction transaction;

    @BeforeClass
    public static void createTransaction(){
        BigDecimal amount = new BigDecimal(12.3343);
        transaction = new Transaction(amount.toString(),
                "2010-10-02T12:23:23Z");
    }

    @Test
    public void getTransactionStatus() throws Exception {

        //final String transactionJson = json.write(transaction).getJson();
        Gson gson = new Gson();
        String jsonRequest = gson.toJson(transaction);
        mockMvc
                .perform(post("/api/transactions")
                        .content(jsonRequest)
                        .contentType(APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());
    }

推荐阅读