spring - 是否可以将“JGiven Spring”与“JGiven JUnit 5”结合使用?
问题描述
不幸的是,我的方法没有自动装配 spring bean。我使用了 JGiven 的 0.17.0 版本。
以下测试失败并出现 NullPointerException,因为 HelloWorldStage 类中的 spring bean 'messageService' 为空。
摇篮:
testCompile group: 'com.tngtech.jgiven', name: 'jgiven-junit5', version: '0.17.0'
testCompile group: 'com.tngtech.jgiven', name: 'jgiven-spring', version: '0.17.0'
测试类:
import com.tngtech.jgiven.annotation.ScenarioStage;
import com.tngtech.jgiven.integration.spring.EnableJGiven;
import com.tngtech.jgiven.junit5.JGivenExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@SpringBootTest(classes = {HelloWorldTest.class})
@Configuration
@EnableJGiven
@ComponentScan(basePackages = "sample.jgiven.*")
@ExtendWith(JGivenExtension.class)
class HelloWorldTest {
@ScenarioStage
private HelloWorldStage helloWorldStage;
@Test
void sayHello() {
helloWorldStage
.given().recipient("Bob")
.when().sendMessage()
.then().answer();
}
}
阶段:
import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.Quoted;
import com.tngtech.jgiven.annotation.ScenarioState;
import com.tngtech.jgiven.integration.spring.JGivenStage;
import org.springframework.beans.factory.annotation.Autowired;
@JGivenStage
class HelloWorldStage extends Stage<HelloWorldStage> {
@Autowired
private MessageService messageService;
@ScenarioState
private String recipient;
HelloWorldStage recipient(@Quoted String name) {
this.recipient = name;
return self();
}
public HelloWorldStage sendMessage() {
return self();
}
public String answer() {
return messageService.createMessage(recipient);
}
}
春豆:
import org.springframework.stereotype.Service;
@Service
public class MessageService {
public String createMessage(String recipient) {
return "Hello " + recipient;
}
}
解决方案
是的,这是可能的,但是,它目前需要一种解决方法。你必须做以下两件事:
- 从 jgiven-spring 依赖项中排除 jgiven-junit
- 创建新的基类 SpringJunit5ScenarioTest 扩展 SpringExtension 和 JGivenExtension,还实现 BeanFactoryAware 以设置场景的舞台创建者。
另请参阅https://github.com/TNG/JGiven/issues/369了解详情。
JGiven 的下一个主要版本将提供开箱即用的 Spring 5 支持。
推荐阅读
- oracle - 多列的内连接并在 INSERT INSTO....SELECT 中使用
- android - 将 int 数组绑定到列表视图
- javascript - javascript动态添加多组文本框并将它们全部重复
- php - 在 drupal8 中使用特定术语保存分类术语 id
- google-translate - Google Cloud Translator API 归属的自定义协议
- c++ - 调查小型转储而不从进程中获取所有二进制文件
- swift - tableView 重新加载但不更新/更改 UI
- kotlin - Kotlin RxJava2 Flowable PublishSubject 不发出数据 onNext
- java - Sns @NotificationMessage 不适用于不同于 String 的类型
- vb.net - vb.net 使用变量动态创建表单名称