我正在为一个Web应用程序编写单元测试,我遇到了服务层的问题。 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,但存在repository和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;
}
}
如果要从spring-context获取bean,则需要此注释。在您的实现中,您已经使用模拟的存储库创建了一个服务。默认情况下,模拟对象返回null。您可以使用Mockito.when()
覆盖默认行为。