春季安全测试@WithMockUser不工作



我正在为我的应用程序编写单元测试,我在服务中所做的其中一个步骤是从SpringSecurityContext中获取当前经过身份验证的用户。

我知道,如果我想模拟Spring安全认证,我可以使用@WithMockUser,但它不适合我,因为当测试方法达到getAuthentication()方法调用时,它总是返回null…

我已经搜索了许多SO问题和许多博客帖子,但没有一个有解决方案。我用@ExtendWith(MockitoExtension.class)注释我的测试类

我想避免必须写4行来模拟单个方法调用

//mock Authentication
//mock Principal
//当springcontexthholder . getcontext()。getAuthentication→return Authentication
//getPrincipal() ->返回主

编辑:

测试类

@ExtendWith(MockitoExtension.class)
public class SegmetnServiceTest {

@InjectMocks
private SegmentService service;

@Test
void testWithMockUser() {
//given
UpdateSegmentReq request = new UpdateSegmentReq();
String name = "TEST"
request.setName(name)
//when
SegmentNode segment = service.updateSegment(request);
//then
assertEquals(segment.getName(), name)
}
}

服务类

public class SegmentService {
private SegmentRepository repository;
SegmentNode updateSegment(String code){
SegmentNode segment = repository.findByCode(code);
String userId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
segment.updatedBy(userId);

return segment;
}
}

问题是,即使我用@WithMockUser注释我的测试方法,当它到达服务方法时,getAuthentication是空的,getPrincipal抛出NPE。

您应该使用@ContextConfiguration将Spring安全测试配置加载到应用程序上下文中(假设您也有spring-test作为依赖项)。

您可以使用注释@SpringJUnitConfig来组合所需的注释——@ExtendWith(SpringExtension.class)@ContextConfiguration——以在测试中设置spring测试。

最新更新