【问题标题】:JUnit test for RestController with JDBCTemplate in SpringBoot在 Spring Boot 中使用 JDBCTemplate 对 Rest Controller 进行 JUnit 测试
【发布时间】:2021-02-02 04:08:56
【问题描述】:

我的控制器如下所示:

@Autowired
JdbcTemplate jdbcTemplate;

@RequestMapping(value="/1",method=RequestMethod.POST)
public ResponseEntity<List<Map<String, Object>>> abc(@RequestBody String[] arr) {
    List<Map<String, Object>> result =jdbcTemplate.queryForList("select * from Table_Name where  COL1='"+arr[1]+"' and  COL2='"+arr[2]+"' order by COL3");
    
    return new ResponseEntity<List<Map<String,Object>>>(result,HttpStatus.OK);
}

我写的测试类如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MainClass.class)
@WebAppConfiguration

public class TestWebApplication {
    protected MockMvc mvc;
       @Autowired
       WebApplicationContext webApplicationContext;

       protected void setUp() {
          mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
       }

    @Test
    public void testabc() throws Exception{
         mvc.perform(post("/1").andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")));
      
    }

andExpect 出错,要求强制转换该方法。

请任何人帮助我编写 JDBC 模板的 Junit 测试用例。

提前致谢。

【问题讨论】:

    标签: spring-boot junit


    【解决方案1】:

    将测试类更新到以下:

     @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = MainClass.class)
    @WebAppConfiguration
    public class TestWebApplication {
        
         @Autowired
          private WebApplicationContext webApplicationContext;
          private MockMvc mockMvc;
    
          @Before
          public void setUp() {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
          }
    
        @Test
        public void testabc() throws Exception{
            String[] arr ={"A","B"};
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
            ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
            String requestJson=ow.writeValueAsString(arr );
            mockMvc.perform( post("/1").contentType( MediaType.APPLICATION_JSON).content(requestJson));
        
        }
    

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2017-08-01
      • 2021-12-17
      • 2012-10-24
      • 2017-01-23
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多