引入依赖

  1. <dependency>
  2. <groupId>com.pig4cloud</groupId>
  3. <artifactId>pig-common-test</artifactId>
  4. <version>${last.version}</version>
  5. <scope>test</scope>
  6. </dependency>

单元测试 Controller 接口

  • 指定单元测试 token来源

    1. # 配置在 test/resources/application.yml
    2. security:
    3. oauth2:
    4. client:
    5. access-token-uri: http://pig-gateway:3000/oauth/token
  • 模拟测试controller 接口 ```java import com.pig4cloud.pig.test.annotation.WithMockOAuth2User; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext;

import static com.pig4cloud.pig.test.kit.OAuthMockKit.token; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class) @SpringBootTest public class SysLogControllerTest {

  1. private MockMvc mvc;
  2. @Autowired
  3. private WebApplicationContext applicationContext; // 注入WebApplicationContext
  4. @Before
  5. public void setUp() {
  6. this.mvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
  7. }
  8. @Test
  9. @SneakyThrows
  10. @WithMockOAuth2User
  11. public void testMvcToken() {
  12. mvc.perform(delete("/log/1").with(token())).andExpect(status().isOk());
  13. }

}

  1. - 模拟测试 FeignClient 传递 token
  2. 直接注入 FeignClient 实现即可 使用 **@WithMockOAuth2User 注解测试类即可**<br />**
  3. <a name="2Xp6r"></a>
  4. ## **WithMockOAuth2User 属性说明**
  5. - 当前用例获取 token 使用的用户名
  6. ```java
  7. String username() default "admin";
  • 当前用例获取 token 使用的密码
    1. String password() default "123456";