我在使用 @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/