在单元测试期间,Spring Boot MongoDB Repository为null

时间:2018-02-26 05:00:06

标签: java mongodb unit-testing spring-boot repository

我已经有一段时间了,但无法理解。当运行应用程序正常时,repo注入罚款,但是当尝试进行弹簧启动单元测试时它永远不会注入。这是代码:

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);
    }

}

我基本上试图按照本指南的例子:https://springframework.guru/configuring-spring-boot-for-mongo/

谢谢大家解决我确信这是一个非常基本的错误。

编辑:我认为问题是当我运行测试类时弹出上下文没有启动...

编辑:这是启动器类:

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);
	}
}

1 个答案:

答案 0 :(得分:0)

试试这个

@SpringBootTest(classes= {Application.class})

其中Application.class是您编写SpringApplication.run代码的地方。

public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }