【发布时间】:2020-08-28 19:20:22
【问题描述】:
我正在使用以下代码来测试带有 Spring 证券的 rest 控制器。 WebMvcTest 用于执行测试。我不想使用 SpringBootTest 注解,因为它会使启动整个应用程序上下文的测试变得非常缓慢。
package org.project.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.project.model.SampleBean;
import org.project.service.SampleBeanService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class) // tells JUnit to run using Spring’s testing support.
@WebMvcTest(SampleBeanRestController.class)
@AutoConfigureMockMvc
public class SampleBeanRestControllerTest {
@MockBean
private SampleBeanService SampleBeanService;
@Autowired
private MockMvc mockMvc;
public MockMvc getMockMvc() {
return mockMvc;
}
@Test
@WithMockUser(username = "user", password = "password", roles = "USER")
public void deleteSampleById() throws Exception{
getMockMvc().perform(delete("/api/sample/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
我收到以下错误:
Parameter 0 of constructor in org.project.config.WebSecurityConfig required a bean of type 'org.project.security.jwt.TokenProvider' that could not be found.
我怎样才能绕过这个? TokenProvider 已导入 WebSecurityConfig。谢谢。
【问题讨论】:
-
可以显示测试类代码吗?
-
@Deadpool。我进行了更新。谢谢。
标签: java spring-boot junit spring-security