I am trying to write a very basic test for my repository/service classes, but for reasons I cannot seem to figure out, my autowired repository is always null.
Here is the Repo class
public interface RuleRepository extends JpaRepository<Rule, UUID> {
public Optional<Rule> findByName(String name);
}
And the test
@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);
}
}
}
Does anyone have any ideas? The test always passes...
Edit: I'm not sure if this is an error that deserves a new post or not, but running with the annotaion @RunWith(SpringRunner.class)
yields the error RulesTest.testSaveOneRule ? IllegalState Failed to load ApplicationContext...
RulesTest.testSaveOneRule ? IllegalState Failed to load ApplicationContext...
The content of 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);
}
}
For testing Repositories you should have the annotations:
@DataJpaTest
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MyApplication.class)
I am noticing that you are missing this annotation @RunWith(SpringRunner.class)
I was following this page and I could do it https://grokonez.com/testing/datajpatest-with-spring-boot
if you are using JPA add in class Test @DataJpaTest. Ex.:
@DataJpaTest
public class CategoriaServiceTest {
@Autowired
private CategoriaRepository repository;
@Test
public void test() {
Categoria categoria = new Categoria(null, "Teste");
Categoria categoriaSaved = repository.save(categoria);
assertEquals(categoria.getNome(), "Jefferson");
}
}
The solution for me (to be able and load the application context also) was to use the following annotation:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class TestDiscountRepository {
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.