【问题标题】:Junit 5 doesn't see controllers URL when using @WebMvcTest - Mockito and Spring BootJunit 5 在使用 @WebMvcTest - Mockito 和 Spring Boot 时看不到控制器 URL
【发布时间】:2021-02-26 21:04:19
【问题描述】:

我为SystemAuthorityController 创建了一个测试类,因为我只需要加载部分上下文。

我使用了@WebMvcTest 注释并指定了要测试的控制器(我也尝试了所有控制器,但也没有用)。

@WebMvcTest(SystemAuthorityController.class)
@TestPropertySource("classpath:application.properties")
public class SystemAuthorityControllerTest 

当我尝试从此控制器调用任何端点时,我得到404,因为找不到端点。

经过一番研究,我找到了解决方案 - 即在我需要的控制器中添加 @Import 注释,之后一切正常,找到了 URL。

@WebMvcTest(SystemAuthorityController.class)
@Import({SystemAuthorityController.class})
@TestPropertySource("classpath:application.properties")
public class SystemAuthorityControllerTest 

我的问题是为什么我需要显式导入控制器我想测试,因为我从未见过此注释用于此目的(我也不认为我应该这样使用) .据我了解,WebMvcTest 应该加载所有控制器 bean。

【问题讨论】:

    标签: spring mockito junit5


    【解决方案1】:

    如果在同一个模块中工作,则无需显式导入控制器。

    如果您收到 404,可能是由于其他原因。 [需要看日志]

    这是 ControllerTest 的基本工作示例。 [万一你错过了什么]

    @RunWith(MockitoJUnitRunner.class)
    @AutoConfigureMockMvc
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class AControllerTest {
        
        @InjectMocks
        AController aController;
        
        @Autowired
        MockMvc mockMvc;
        
        @Mock
        AService aService;
            
        @Before
        public void setUp() {
            this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();
    
        }
        
        @Test
        public void aTest() throws Exception {
            ObjectMapper objectMapper = new ObjectMapper();
            ADetails user = new ADetails();
            user.setId("1234");
            this.mockMvc.perform(MockMvcRequestBuilders.post("/a/signin").header("Referer", "test")
                                                       .contentType(MediaType.APPLICATION_JSON)
                                                       .content(objectMapper.writeValueAsString(user)))
                        .andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 2018-07-21
      • 2019-07-01
      • 2019-03-23
      • 2020-07-29
      • 2021-11-21
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多