junit 测试中的 JPA 存储库为空

我正在尝试为我的存储库/服务类编写一个非常基本的测试,但由于我似乎无法弄清楚的原因,我的自动装配存储库始终为空。


这是回购类


public interface RuleRepository extends JpaRepository<Rule, UUID> {   

    public Optional<Rule> findByName(String name);

}

和测试


@DataJpaTest

@ContextConfiguration(classes = MyApplication.class)

public class RulesTest {

    @Autowired

    private RuleRepository ruleRepository;  


    @Test

    public void testSaveOneRule() {

        if (ruleRepository == null) {

            System.err.println("HERE");

            assertTrue(true);

        } else {

              assertTrue(false);

          }

    }

}

有没有人有任何想法?考试总是通过...


编辑:我不确定这是否是一个值得发布新帖子的错误,但使用注释运行会@RunWith(SpringRunner.class)产生错误RulesTest.testSaveOneRule ? IllegalState Failed to load ApplicationContext...


MyApplication.class 的内容


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class MyApplication {


    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);

    }

}


隔江千里
浏览 206回答 3
3回答

弑天下

对于测试存储库,您应该具有注释:@DataJpaTest&nbsp;@RunWith(SpringRunner.class)&nbsp;@SpringBootTest(classes=MyApplication.class)

临摹微笑

我注意到您缺少此注释 @RunWith(SpringRunner.class)我一直在关注这个页面,我可以做到https://grokonez.com/testing/datajptest-with-spring-boot

慕村225694

如果您使用 JPA,请添加类 Test @DataJpaTest。前任。:@DataJpaTestpublic class CategoriaServiceTest {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private CategoriaRepository repository;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @Test&nbsp; &nbsp; public void test() {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Categoria categoria = new Categoria(null, "Teste");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Categoria categoriaSaved = repository.save(categoria);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(categoria.getNome(), "Jefferson");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java