NullPointerException无法调用空对象的方法

时间:2019-06-09 21:18:56

标签: spring jpa spock

我正在尝试编写一个简单的测试,该测试将使用service测试我所有的操作,但问题是我不知道为什么会收到此错误,甚至无法运行一个错误测试。

@SpringBootTest
class EpisodeServiceTest extends Specification {

    @Autowired
    private EpisodeService episodeService

    def "should create episode and save in in the database"() {
        when:
        Episode episode = new Episode("title", "description")

        and:
        episodeService.addEpisode(episode)

        then:
        episode == episodeService.findById(episode.id)
    }
}
@Service
@Transactional
public class EpisodeService {

    private EpisodeRepository episodeRepository;

    @Autowired
    public EpisodeService(EpisodeRepository episodeRepository) {
        this.episodeRepository = episodeRepository;
    }

    public Episode findById(long id) {
        return episodeRepository.findById(id).orElse(null);
    }

    public List<Episode> findAll() {
        return episodeRepository.findAll();
    }

    public void addEpisode(Episode episode) {
        if (episode != null)
            episodeRepository.save(episode);
    }

    public void deleteEpisodeById(long id) {
        Episode episode = findById(id);
        if (episode != null)
            episodeRepository.delete(episode);
    }
}

该存储库只是扩展JpaRepository的简单存储库,我的问题是如何使用spock测试jpa实体?我做错了,因为我是第一次尝试这样做,所以我早些时候在JUnit中编写了一个简单的测试,但我想尝试使用spock。

2 个答案:

答案 0 :(得分:0)

解决方案是将这种依赖关系添加到maven中

        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-spring</artifactId>
            <version>1.3-groovy-2.5</version>
            <scope>test</scope>
        </dependency>

仅添加spock-core是不够的。

答案 1 :(得分:0)

您的测试班级缺少注释@RunWith(SpringRunner.class)

@SpringBootTest
@RunWith(SpringRunner.class)
class EpisodeServiceTest extends Specification {