简体   繁体   English

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

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

I'm having trouble running a test with @BeforeClass and @Autowired . 我在使用@BeforeClass@Autowired进行测试时遇到麻烦。 I am using the H2 database in running the tests and would like to persist a list before running each test method. 我在运行测试时使用的是H2数据库,并希望在运行每种测试方法之前保留一个列表。 However, I get nullpointer . 但是,我得到nullpointer Can anybody help me? 有谁能够帮助我?

Segue minha classe de teste: 塞斯特·米哈·德·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() {

     ...

}

You "can't" create objects from a static field 您“无法”从静态字段创建对象

EDIT: as rightly noted by friend 'lealceldeiro' - I should slightly elaborate. 编辑:正如朋友“ lealceldeiro”所正确指出的-我应该稍作阐述。

@Autowire annotation is used when you want to inject ie field right after construction of a bean(object), before any config methods are invoked. 如果要在构造bean(对象)之后,调用任何配置方法之前立即注入ie字段,则使用@Autowire批注。 So you want Spring container to take care of the object creation so you can only 'wire' them 因此,您希望Spring容器负责对象的创建,因此只能“连接”它们

If you were to 'wire' a static object - well @autowire purpose is sort of defeated, as once you start using static methods, you no longer need to create an instance of object. 如果您要“连接”静态对象,那么@autowire的用途就会被破坏,因为一旦开始使用静态方法,就不再需要创建对象的实例。

When I say you can't well... technically you can but whats the point + it may be recorded as a bug for example: 当我说您不能很好...从技术上讲您可以,但是有什么意义,它可能会记录为错误,例如:

@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