I have been at this for a while but can't figure it out. The repo injects fine when running the app normal, but when trying to do a spring boot unit test it never injects. Here is the code:
package com.g2p.g2prestservice.repositories; import com.g2p.g2prestservice.model.User; import org.springframework.data.mongodb.repository.MongoRepository; public interface UserRepository extends MongoRepository<User, Integer> { }
package com.g2p.g2prestservice.repositories; import com.g2p.g2prestservice.model.User; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest public class UserRepositoryTest { @Autowired UserRepository userRepository; @Test public void testInsertUser() { User user = new User("fake@email.com", "fakePassword"); userRepository.save(user); assertEquals(userRepository.count(), 1); } }
I am essentially trying to follow this guide as example: https://springframework.guru/configuring-spring-boot-for-mongo/
Thank you all for solving what I am sure is a very elementary mistake.
EDIT: I THINK the problem is that the spring context isn't launching when I run the test class...
EDIT: Here is launcher class:
package com.g2p.g2prestservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication public class G2pRestServiceApplication { public static void main(String[] args) { SpringApplication.run(G2pRestServiceApplication.class, args); } }
try this
@SpringBootTest(classes= {Application.class})
where Application.class is where you wrote you SpringApplication.run code.
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
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.