Mockito + TestNG + String - 在没有自动装配的情况下测试不起作用

时间:2017-01-04 08:52:58

标签: java spring mockito testng spring-data-jpa

我正在为网络应用编写单元测试,而且我遇到了服务层问题。 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为空,但存在存储库和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;
}
}

1 个答案:

答案 0 :(得分:1)

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