小编Man*_*dan的帖子

如何为测试场景的 @Service 方法启用/禁用 @EnableGlobalMethodSecurity

我正在与Spring FrameworkSpring Security

关于测试

@Controller 对于具有 安全性的一组测试类,.apply(springSecurity()使用@WithUserDetails(value="something")

@Before
public void setUp(){
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                             .apply(springSecurity())// <---
                             .build();
}
Run Code Online (Sandbox Code Playgroud)

对于没有安全性的其他测试类集,因此不使用@Controller .apply(springSecurity()) @WithUserDetails(value="something")

@Before
public void setUp(){
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)                              
                             .build();
} 
Run Code Online (Sandbox Code Playgroud)

到目前为止,所有关于@Controller 没有安全的情况都可以正常工作。

问题在于@Service,当@EnableGlobalMethodSecurity定义并且@Service方法用 注释时@PreAuthorize("hasRole('ROLE_ADMIN')"),不需要安全性的所有其他测试现在都会失败:@Service

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: 
    An Authentication object was not found in the SecurityContext 
Run Code Online (Sandbox Code Playgroud)

当然是因为@Test …

spring spring-security

3
推荐指数
1
解决办法
1392
查看次数

如何覆盖通过PasswordEncoderFactories创建的默认BCryptPasswordEncoder?

我知道在 Spring Security 中会出现以下情况:

There was an unexpected error (type=Internal Server Error, status=500).
There is no PasswordEncoder mapped for the id "null"
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Run Code Online (Sandbox Code Playgroud)

解决方案是定义一个PasswordEncoder. 为了简单起见,可以定义以下内容:

There was an unexpected error (type=Internal Server Error, status=500).
There is no PasswordEncoder mapped for the id "null"
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Run Code Online (Sandbox Code Playgroud)

现在,该方法在幕后createDelegatingPasswordEncoder()是如何定义的(到目前为止,直到 Spring Security 5.4.2 为止)(有关更多详细信息,请参阅PasswordEncoderFactories类):

@Bean
PasswordEncoder encoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
Run Code Online (Sandbox Code Playgroud)

现在关于 …

spring-security bcrypt

3
推荐指数
1
解决办法
2280
查看次数

Spring AOP-@Pointcut:@Test方法的@Before建议不起作用

我正在与:

  • Spring Framework 4.3.2
  • AspectJ 1.8.9
  • JUnit的
  • 摇篮

该项目基于多模块。

src/main/javamain)中,我有一些@Aspect课程,它们的工作原理如何。我可以通过运行时和测试来确认

现在我需要通过日志记录显示@Test执行的方法名称的JUnit

因此,在src/test/javatest)中,我具有以下内容:

class TestPointcut {

    @Pointcut("execution(@org.junit.Test * *())")                         
    public void testPointcut(){}

}

@Aspect
@Component
public class TestAspect {

    private static final Logger logger = LoggerFactory.getLogger(TestAspect.class.getSimpleName());

    @Before(value="TestPointcut.testPointcut()")
    public void beforeAdviceTest(JoinPoint joinPoint){
        logger.info("beforeAdviceTest - Test: {} - @Test: {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName() );
    }

}
Run Code Online (Sandbox Code Playgroud)

观察第二类@Aspect@Component因此Spring可以识别它。

注意:我可以确认如果我写错了@Pointcut语法或表达式,我会得到错误。

问题是当我执行我的@Test方法时,对于TestAspect该类的@Before建议永远不会起作用。 …

junit aop aspectj spring-aop

2
推荐指数
1
解决办法
6105
查看次数

如何使用自定义@Rule正确配置@RunWith(Parameterized.class)+ SpringClassRule + SpringMethodRule?

我正在使用Spring Framework4.3.x和JUnit4,我有以下结构

@Transactional
@WebAppConfiguration
@RunWith(Parameterized.class)
@ContextConfiguration(classes={RootApplicationContext.class, ServletApplicationContext.class})
@TestExecutionListeners(listeners={LoggingTestExecutionListener.class}, mergeMode=MergeMode.MERGE_WITH_DEFAULTS)
public class CompleteTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();
Run Code Online (Sandbox Code Playgroud)

因此组合:

  • @RunWith(Parameterized.class)+ SpringClassRule+SpringMethodRule

工作如何预期.

TestRule通过ExternalResource以下方式创建了一个自定义:

@Component
public class CompleteRule extends ExternalResource {

    private static final Logger logger = LoggerFactory.getLogger(CompleteRule.class.getSimpleName());

    private final WebApplicationContext webApplicationContext;

    private final Environment environment;

    private MockMvc mockMvc;

    public CompleteRule(WebApplicationContext webApplicationContext, Environment environment) {
        this.webApplicationContext = webApplicationContext; …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-test junit5

2
推荐指数
1
解决办法
694
查看次数

Eclipse:如何删除非 Java 文件所有行的尾随空格?

在 Eclipse IDE(或在我的情况下STS)的 java 文件 about: remove trailing white space on all lines我能够执行以下操作:

在此处输入图片说明

实际上是如何描述的:

因此从上图可以看出:

  • Remove trailing white spaces on all lines

直到一切正常,但为了开发,我们有其他扩展名的文件。因此,对于非 java 文件,我需要具有相同的功能,例如:.xml, .js, .gradle, .html, .css, .properties,.sql文件等。

我找不到一个特定的部分来完成这个。

我怎样才能完成这个必需的配置?

eclipse spring-tool-suite

2
推荐指数
1
解决办法
1793
查看次数

Spring Boot 的 Spring Security 默认凭据是什么?

Spring Boot我正在使用,spring-data-rest-hal-browser一切似乎都很好,除了当我尝试点击 URL 时:http://localhost:8080我被重定向到http://localhost:8080/login使用 HAL 浏览器来导航我的端点,然后我看到一个屏幕,要求输入用户和密码我没有。

登录 Spring Security 的默认凭据是什么?如何更改它们或禁用登录选项?

这是我正在使用的依赖项:

<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这是登录屏幕:

在此输入图像描述

java spring hateoas spring-boot

2
推荐指数
1
解决办法
6521
查看次数

使用 @Sql &amp; H2 的 Spring Boot 测试给出了 JdbcSQLIntegrityConstraintViolationException: 唯一索引或主键冲突

我有一个简单的 Spring Boot (2.6.1) 测试,它抛出:

 JdbcSQLIntegrityConstraintViolationException: 
 Unique index or primary key violation
Run Code Online (Sandbox Code Playgroud)

该测试从 加载数据test/resources/data.sql,其中只有一条语句:

INSERT INTO country (name) VALUES ('Italy');
Run Code Online (Sandbox Code Playgroud)

测试类是:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class FailingTest {

   @Test
   @Sql("/data.sql")
   void test(){
       assertTrue(true);
   }
}
Run Code Online (Sandbox Code Playgroud)

域类是:

@Entity 
public class Country {
   @Id
   @GeneratedValue(strategy = IDENTITY)
   private Integer id;

   @Column(nullable = false, unique = true)
   private String name;
}
Run Code Online (Sandbox Code Playgroud)

application.properties文件包含:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.jpa.defer-datasource-initialization=true
Run Code Online (Sandbox Code Playgroud)

异常消息是:

org.springframework.jdbc.datasource.init.ScriptStatementFailedException:
Failed to execute SQL script statement #1 of class path resource [data.sql]: 
INSERT …
Run Code Online (Sandbox Code Playgroud)

testing hibernate h2 unique-constraint spring-boot-test

2
推荐指数
1
解决办法
4098
查看次数

Java 8:使用文件的供应商抛出"流已经被操作或关闭"

使用JUnitStream我有以下错误消息:

java.lang.IllegalStateException: stream has already been operated upon or closed
Run Code Online (Sandbox Code Playgroud)

我做了一个研究,可以明确的是没有可能重用流

根据这篇文章:

使用Supplier是可以解决这个问题.

所以我目前的代码如下:

    try (Stream<String> stream =  Files.lines(Paths.get(fileName)) ) {

        Supplier<Stream<String>> supplier = () -> stream;

        logger.info("A");
        logger.info("ABC {}", supplier.get().findFirst().get());
        logger.info("B");
        logger.info("XYZ {}", supplier.get().skip(1050).findFirst().get());
        logger.info("C");

        assertThat(supplier.get().count(), is(1051));

    }
    catch (IOException e) {
        logger.error("{}", e.getMessage());
    }
Run Code Online (Sandbox Code Playgroud)

怎么可以看到我用的是supplier.get()与工作Stream(其与本教程根据),但@Test打印,直到,因此@Test在出现故障supplier.get().skip(1050).findFirst().get(),它仍产生相同的错误消息.

我的代码和教程之间的独特区别,mime通过文件工作,教程围绕数组工作.

有什么特别的编辑工作没有任何问题?

Α

我做了以下版本(根据Eugene的代码段)

   try (Stream<String> stream …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

1
推荐指数
1
解决办法
990
查看次数

SpringBootTest.WebEnvironment:什么时候必须使用RANDOM_PORT和DEFINED_PORT?

为了Spring Boot进行测试,它@SpringBootTestSpringBootTest.WebEnvironment枚举一起使用。好吧,根据javadoc,它有4个值。

此外,我已经阅读了“ 测试Spring Boot应用程序”部分

对我来说,很清楚,这NONE是仅MOCK测试服务器端,并通过Web端测试所有服务器端(以解决Spring MVC Test)。直到这里我还好。我都用。

其他两个:RANDOM_PORTDEFINED_PORT与有关to start a full running server,它与“ 正在运行服务器测试”部分(该部分开头的第一段)一致

两个问题:

  • 在哪种情况下必须与full running server?一起使用?
  • 还有什么具体的方案,以强制或者使用RANDOM_PORTDEFINED_PORT

spring-boot

1
推荐指数
1
解决办法
2508
查看次数

尝试在 Ubuntu 服务器中安装/启动 Jenkins - hudson.util.AWTProblem

我正在尝试在 Ubuntu 中安装/启动Jenkins2.303),但现在对于服务器(对于桌面没有问题)

JAVA_HOME以及文件JENKINS_HOME中定义的环境变量.profile

关于Java信息:

java -version
openjdk version "11.0.11" 2021-04-20
OpenJDK Runtime Environment AdoptOpenJDK-11.0.11+9 (build 11.0.11+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK-11.0.11+9 (build 11.0.11+9, mixed mode)

javac -version
javac 11.0.11

which java
/home/user/something/java/openjdk/jdk-11.0.11+9/bin/java
Run Code Online (Sandbox Code Playgroud)

但是对于启动 Jenkins 的第一次执行,会发生以下情况

java -jar jenkins.war --httpPort=9090
Running from: /home/user/something/jenkins/bin/jenkins.war
webroot: EnvVars.masterEnvVars.get("JENKINS_HOME")
2021-07-22 18:15:09.003+0000 [id=1]     INFO    org.eclipse.jetty.util.log.Log#initialized: Logging initialized @1892ms to org.eclipse.jetty.util.log.JavaUtilLog
2021-07-22 18:15:09.374+0000 [id=1]     INFO    winstone.Logger#logInternal: Beginning extraction from war file
2021-07-22 18:15:09.474+0000 [id=1] …
Run Code Online (Sandbox Code Playgroud)

jenkins

1
推荐指数
1
解决办法
1785
查看次数