小编Mil*_*vić的帖子

在JUnit中使用(out)存储库对Spring Boot服务类进行单元测试

我正在开发基于Spring boot的webservice,其结构如下:

控制器(REST) - >服务 - >存储库(如某些教程中所建议的).

我的数据库连接(JPA/Hibernate/MySQL)在@Configuration类中定义.(见下文)

现在我想为我的Service类中的方法编写简单的测试,但我真的不明白如何将ApplicationContext加载到我的测试类中以及如何模拟JPA/Repositories.

这是我走了多远:

我的服务类

@Component
public class SessionService {
    @Autowired
    private SessionRepository sessionRepository;
    public void MethodIWantToTest(int i){
    };
    [...]
}
Run Code Online (Sandbox Code Playgroud)

我的考试班:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class SessionServiceTest {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public SessionService sessionService() {
            return new SessionService();
        }
    }

    @Autowired
    SessionService sessionService;
    @Test
    public void testMethod(){
    [...]
  }
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下例外:

引起:org.springframework.beans.factory.BeanCreationException:创建名为'sessionService'的bean时出错:注入自动连接的依赖项失败; 嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.myApp.SessionRepository com.myApp.SessionService.sessionRepository; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到[com.myApp.SessionRepository]类型的限定bean用于依赖:预期至少有1个bean符合此依赖关系的autowire候选者.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

为了完整性:这是我的@Configuration for jpa:

@Configuration
@EnableJpaRepositories(basePackages={"com.myApp.repositories"})
@EnableTransactionManagement
public class JpaConfig { …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-boot

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

Spring MVC:DeferredResult和ListenableFuture之间的区别?

Spring MVC允许控制器返回DeferredResultListenableFuture(由实现ListenableFutureTask)进行异步响应。有什么不同?我什么时候应该使用它们?

java spring asynchronous spring-mvc

5
推荐指数
2
解决办法
3733
查看次数

将@Future和LocalDate的自定义ConstraintValidator添加到Spring Boot项目

我有一个用于输入日期的Spring MVC表单,输入被发送到Controller并通过标准Spring MVC验证进行了验证。

模型:

public class InvoiceForm {
    @Future
    private LocalDate invoicedate;
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public String postAdd(@Valid @ModelAttribute InvoiceForm invoiceForm, BindingResult result) {
    ....
}
Run Code Online (Sandbox Code Playgroud)

提交表单时,出现以下错误:

public class InvoiceForm {
    @Future
    private LocalDate invoicedate;
}
Run Code Online (Sandbox Code Playgroud)

ConstraintValidator为这种情况实施了自己的程序。但是以某种方式,Spring Boot不会选择它进行验证。

@Component
public class LocalDateFutureValidator implements ConstraintValidator<Future, LocalDate> {

    @Override
    public void initialize(Future future) {
    }

    @Override
    public boolean isValid(LocalDate localDate, ConstraintValidatorContext constraintValidatorContext) {
        LocalDate today = LocalDate.now();
        return localDate.isEqual(today) || localDate.isAfter(today);
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以简单地编写自己的注释并在其中指定验证器,但是不是更干净,更简单的方法吗?

validation spring-mvc bean-validation spring-boot

5
推荐指数
2
解决办法
3497
查看次数

spring boot 1.4,spock和application.properties

我正在尝试使用Spock为我的Spring Boot 1.4.0编写一些测试,并且我的应用程序测试属性文件没有被选中.

我在我的gradle中有这个:

dependencies {

    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile 'org.codehaus.groovy:groovy-all:2.4.1'    
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.spockframework:spock-spring:1.0-groovy-2.4') {
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个

/ src目录/测试/常规/资源:

# JWT Key
jwt.key=MyKy@99
Run Code Online (Sandbox Code Playgroud)

最后我的Spock测试:

@SpringBootTest(classes = MyApplication.class, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("application-test.properties")
public class TokenUtilityTest extends Specification {

    @Autowired
    private TokenUtility tokenUtility

    def "test a valid token creation"() {
        def userDetails = new User(username: "test", password: "password", accountNonExpired: true, accountNonLocked: true,
        );

        when:
        def token = tokenUtility.buildToken(userDetails)

        then:
        token != null
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个测试这个类:

@Component
public class TokenUtility {

    private static final Logger LOG …
Run Code Online (Sandbox Code Playgroud)

spring-test spock spring-boot

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

Spring Boot Integration测试随机自由端口

我能够获得Spring Boot集成以生成随机自由端口以启动自身.但我还需要Redis的免费端口.

@ContextConfiguration(classes = {MyApplication.class}, loader = SpringApplicationContextLoader.class)
@WebIntegrationTest(randomPort = true, value = "server.port:0")
@ActiveProfiles(profiles = {"local"})
public class SegmentSteps {

    private static final String HOST_TEMPLATE = "http://localhost:%s";

    // Needs to be a random open port
    private static final int REDIS_PORT = 6380;

    private String host;
    @Value("${local.server.port}")
    private int serverPort;

    private RedisServer redisServer;

    @Before
    public void beforeScenario() throws Exception {
        host = String.format(HOST_TEMPLATE, serverPort);
        redisServer = RedisServer.builder()
                .redisExecProvider(RedisExecProvider.defaultProvider())
                .port(REDIS_PORT)
                .setting("bind 127.0.0.1")
                .build();
        redisServer.start();
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

关于如何实现这一点的任何想法?

java spring integration-testing spring-test spring-boot

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

目录之间的Apache camel复制文件

我是apache camel和spring boot的新手.我正在编写一个应用程序,我需要将文件从文件夹传输到jms队列.但在此之前,我试图将文件从一个文件夹转移到另一个文件夹,这是没有发生的.在将应用程序作为spring boot应用程序运行时,将创建输入文件夹.如果将文件粘贴到此文件夹中,则不会形成目标文件夹,并且也不会显示日志语句.这是我添加路线的方式:

@SpringBootApplication
public class CamelApplication extends FatJarRouter {

    public static void main(String ... args) {
        SpringApplication.run(CamelApplication.class, args);
    }

    @Override
    public void configure() throws Exception {
        from("file:input?noop=true")
        .log("Read from the input file")
        .to("file:destination")
        .log("Written to output file");
    }
}
Run Code Online (Sandbox Code Playgroud)

java apache-camel spring-boot

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