繁体   English   中英

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

[英]How use @Autowired in test with jUnit?

我在使用@BeforeClass@Autowired进行测试时遇到麻烦。 我在运行测试时使用的是H2数据库,并希望在运行每种测试方法之前保留一个列表。 但是,我得到nullpointer 有谁能够帮助我?

塞斯特·米哈·德·teste

@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() {

     ...

}

您“无法”从静态字段创建对象

编辑:正如朋友“ lealceldeiro”所正确指出的-我应该稍作阐述。

如果要在构造bean(对象)之后,调用任何配置方法之前立即注入ie字段,则使用@Autowire批注。 因此,您希望Spring容器负责对象的创建,因此只能“连接”它们

如果您要“连接”静态对象,那么@autowire的用途就会被破坏,因为一旦开始使用静态方法,就不再需要创建对象的实例。

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

@Component
public class Foo{

    private static Test t;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM