简体   繁体   中英

How use @Autowired in test with jUnit?

I'm having trouble running a test with @BeforeClass and @Autowired . I am using the H2 database in running the tests and would like to persist a list before running each test method. However, I get nullpointer . Can anybody help me?

Segue minha classe de 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.

@Autowire annotation is used when you want to inject ie field right after construction of a bean(object), before any config methods are invoked. So you want Spring container to take care of the object creation so you can only 'wire' them

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.

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

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.

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