gpt4 book ai didi

java - Mockito + TestNG + String - 测试在没有 Autowiring 的情况下无法工作

转载 作者:行者123 更新时间:2023-11-30 06:57:55 25 4
gpt4 key购买 nike

我正在为一个网络应用程序编写单元测试,但我遇到了服务层问题。 App使用Spring Data JPA和H2数据库进行测试。

这是我的测试类:

@WebAppConfiguration
@ContextConfiguration(classes = {TestConfiguration.class})
@TestPropertySource(locations = "classpath:test.properties")
@Transactional
public class AuthorCreateServiceTest extends AbstractTestNGSpringContextTests {

@Mock
private AuthorRepository authorRepository;

private AuthorCreateServiceImpl authorCreateServiceImpl;

private Author firstAuthor;
private Author secondAuthor;

@BeforeClass
public void setUp() {
authorCreateServiceImpl = new AuthorCreateServiceImpl(authorRepository);
firstAuthor = new Author();
firstAuthor.setFirstName("Leo");
firstAuthor.setLastName("Manly");
firstAuthor.setNationality("Mexico");
firstAuthor.setId(3L);
secondAuthor = new Author();
secondAuthor.setFirstName("Zorro");
secondAuthor.setLastName("Plata");
secondAuthor.setNationality("Zambia");
secondAuthor.setId(4L);
}

@Test
public void succesfullySaveAuthorTest() {
Author testAuthor = authorCreateServiceImpl.create(firstAuthor);
Assert.assertEquals(testAuthor.getFirstName(), firstAuthor.getFirstName());
}

@Test
public void failSavingAuthorTest() {
String firstName = "Man";
Author testAuthor = authorCreateServiceImpl.create(secondAuthor);
boolean isEqual = testAuthor.getFirstName().equals(firstName);
Assert.assertFalse(isEqual);
}

}

在此状态下,testAuthor 为 null,但存储库和 createService 对象存在。但是,如果我向 AuthrhorCreateServiceImpl 字段添加 Autowired 注释,它就可以正常工作。

Autowired 是必要的还是我做错了什么?

编辑

测试配置类

@ComponentScan(basePackages = {"com.altkom.library"} )
@Configuration
@TestPropertySource(locations = "classpath:test.properties")
public class TestConfiguration extends JPAConfiguration {

public TestConfiguration(Environment environment) {
super(environment);
}

@Bean(destroyMethod = "shutdown")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase dataBase = builder.setType(EmbeddedDatabaseType.H2).addScript("classpath:import.sql").build();
return dataBase;
}
}

最佳答案

如果要从spring-context获取bean,则需要这个注解。在您的实现中,您创建了一个带有模拟存储库的服务。模拟对象默认返回 null。您可以使用 Mockito.when() 覆盖默认行为。

关于java - Mockito + TestNG + String - 测试在没有 Autowiring 的情况下无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com