Reputation: 529
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...
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);
}
}
Upvotes: 6
Views: 19679
Reputation: 409
I am noticing that you are missing this annotation @RunWith(SpringRunner.class)
Upvotes: 1
Reputation: 617
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 {
...
Upvotes: 0
Reputation: 11
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");
}
}
Upvotes: 1
Reputation: 61
For testing Repositories you should have the annotations:
@DataJpaTest
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MyApplication.class)
Upvotes: 5