繁体   English   中英

如何使用 JdbcTemplate 为我的 Rest controller 编写单元测试 class

[英]How to write unit test class for my Rest controller with JdbcTemplate

我是 Spring 引导和 junit 的新手。 我在 Spring Boot 中有一个 Rest 服务,我在其中接收请求,使用请求参数查询数据库,接收查询结果并将其作为响应发送。

我的 controller 代码是这样的:

@Autowired
JdbcTemplate mTemplate;

@GetMapping("/myservice")
    public String getGreeting2(@RequestParam(value = "name") String name) {
        //DO the query using mTemplate;
    }

我的 JdbcTemplate 像这样在单独的 class 中被实例化为 bean

@Bean
public JdbcTemplate dataSource(){
         BasicDataSource ds = new BasicDataSource();
         ds.setDriverClassName(....);
         ds.setUrl(...);
         ds.setUserName(...);
         ds.setPassword(...);
         return new JdbcTemplate(ds);
}

我的代码运行良好。

现在我想使用 JUnit4 为我的 controller 编写单元测试。 我使用 MockMvc 发送请求,但我的单元测试从未起飞。 它总是抛出异常说,“无法解析 bean 数据源......无法加载合适的驱动程序类”

我尝试在 src/test/java 内的 application.properties 文件中提供数据源详细信息,但它不起作用。 我想我错过了一些基本的过程。 请指导我使用数据源为 rest controller 编写 junit 测试需要采取哪些步骤。 像这样的东西:

@Runwith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyRestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/myservice").param("name", "..."))
                .andExpect(status().isOk());
                
    }

PS 在 Rest controller 的主 class 中没有数据源,测试运行良好。

在这种情况下,您要做的是集成测试,请在测试 class 中尝试使用此注释:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class)
    @WebAppConfiguration

但也许您只想测试您的 controller,在这种情况下,您可以像这样模拟 JdbcTemplate:

    @InjectMocks
    private YourController yourController;

    @Mock
    private JdbcTemplate mTemplate;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        MonitoringHelper.initMocks();
        intelligencePostFilter = new IntelligencePostFilter(intelligenceService);
        when(mTemplate.methodX()).thenReturn(....);
    }

在这种情况下,没有用于测试 class 的注释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM