在我的资源服务器中,我有一些通过PreAuthorize保护的端点:
@PreAuthorize("isAuthenticated()")
或
@PreAuthorize("hasAuthority('admin')")
我的资源服务器:
@SpringBootApplication
public class ResourceServerApplication extends SpringBootServletInitializer
一些配置
@Configuration
@EnableWebMvc
public class ResourceServerWebConfig implements WebMvcConfigurer {}
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfigJwt extends ResourceServerConfigurerAdapter {}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {}
我尝试编写一些集成测试。我有一个抽象测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-test.properties")
public abstract class AbstractTest {
@Autowired
private WebApplicationContext context;
protected MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.alwaysDo(print())
.apply(springSecurity())
.build();
}
HttpHeaders headers = new HttpHeaders();
ObjectMapper mapper = new ObjectMapper();
}
和一些测试:
public class MediaTest extends AbstractTest {
String baseUrl = "/media";
@Test
@WithMockUser(roles = "admin")
public void testRetrieveMedia() throws Exception {
MvcResult response = mvc.perform(get(baseUrl + "/all")).andReturn();
response.getResponse().getContentAsString();
}
@Test
@WithMockUser(roles = "user")
public void testSaveMedia() throws Exception {
String json = "{..}";
MvcResult response = mvc.perform(post(baseUrl).with(user("john@example.com")).content(json).contentType(MediaType.APPLICATION_JSON)).andReturn();
response.getResponse().getContentAsString();
}
}
两个测试都返回
{“错误”:“未经授权”,“错误说明”:“完整身份验证为 需要访问该资源”}
我已经阅读了很多有关该主题的文章,并尝试了使用@ContextConfiguration @WebAppConfiguration @EnableAutoConfiguration @WebMvcTest进行的许多组合……但是找不到有效的组合。
当我尝试
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest
@ActiveProfiles(profiles = "test")
public abstract class AbstractTest {...}
我遇到了错误
没有符合条件的Bean类型 'org.springframework.mail.javamail.JavaMailSender'可用
有什么主意吗?
Thx