java - 如何在 jUnit 测试中使用@Autowired?

标签 java spring junit

我在使用 @BeforeClass@Autowired 运行测试时遇到问题。我在运行测试时使用 H2 数据库,并希望在运行每个测试方法之前保留一个列表。但是,我得到了空指针。有人可以帮助我吗?

继续测试:

@RunWith(SpringRunner.class)
@DataJpaTest
public class TestaContaRepository {
    @Autowired
    private static TerritorioRepresentanteRepository representanteRepository;

    @BeforeClass
    public static void setup() {
        Conta c1 = new Conta();
        c1.setTipo(Tipo.CONTA);
        c1.setNome("XPTO");

        Conta c2 = new Conta();
        c2.setTipo(Tipo.CONTA);
        c2.setNome("FOO");

        Conta c3 = new Conta();
        c3.setTipo(Tipo.CONTATO);
        c3.setNome("BAA");

        Conta c4 = new Conta();
        c4.setTipo(Tipo.CONTA);
        c4.setNome("DAA");

        TerritorioRepresentante tr1 = new TerritorioRepresentante();
        tr1.setId(1L);
        tr1.setContas(Arrays.asList(c1, c2));

        TerritorioRepresentante tr2 = new TerritorioRepresentante();
        tr2.setId(2L);
        tr2.setContas(Arrays.asList(c2, c3, c4));

        TerritorioRepresentante tr3 = new TerritorioRepresentante();
        tr3.setId(3L);
        tr3.setContas(Arrays.asList(c1, c2, c3, c4));

        List<TerritorioRepresentante> territorios = Arrays.asList(tr1, tr2, tr3);
        representanteRepository.saveAll(territorios);
    }

@Test
public void quando_BuscarPorContasDoRepresentante_RetornarListaDeContasPaginada() {

     ...

}

最佳答案

您“不能”从静态字段创建对象

编辑:正如 friend “lealceldeiro”正确指出的那样 - 我应该稍微详细说明一下。

当您想要在构建 bean(对象)之后、调用任何配置方法之前注入(inject)即字段时,使用 @Autowire 注释。因此,您希望 Spring 容器负责对象创建,这样您就只能“连接”它们

如果您要“连接”静态对象 - 那么 @autowire 的目的有点失败,因为一旦您开始使用静态方法,您就不再需要创建对象的实例。

当我说你不能......从技术上讲你可以,但有什么意义+它可能会被记录为错误,例如:

@Component
public class Foo{

    private static Test t;

    @Autowired
    public void setTest(Test test) {
        Foo.t = test;
    }
}

关于java - 如何在 jUnit 测试中使用@Autowired?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634169/

相关文章:

java - 如何使用 Spring Boot 从 S3 下载 json 文件?

java - Spring 中的@Import 与@ContextConfiguration

java - 如何在另一个类中模拟一个类junit mockito

java - Java 程序的输出

Java 返回类型与 WebCrawler.visit(Page) 不兼容

java - int 数组的通用交换方法

Java - 将对象移动到LinkedList的前面

java - Tomcat 7 中部署的 Spring Boot WAR 尝试执行奇怪的自动 @Resource 查找

安卓 : instumentation testing for app widgets

android - 如何在 Android 上运行 ProGuard 测试?