mockito+testng+string-test在没有autowired的情况下不能工作

rjzwgtxy  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(301)

我正在为一个web应用程序编写单元测试,但服务层有问题。应用程序正在使用spring数据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 为空,但存储库和 createService 对象存在。但如果我加上 Autowired 注解到 AutrhorCreateServiceImpl 菲尔德,很好用。
Autowired 有必要还是我做错了什么?
编辑
testconfiguration类

@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;
}
}
2w3kk1z5

2w3kk1z51#

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

相关问题