@PostConstruct方法的空指针异常?

时间:2016-10-26 22:49:36

标签: java spring

我正在使用Spring在Java中开发一个小应用程序,所以我有这个服务:

public class AccountService implements UserDetailsService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private BlogRepository blogRepository;

    @Autowired
    private ImageService imageService;

    @PostConstruct
    protected void initialize() throws IOException {
        Account user = new Account("user", "demo", "ROLE_USER");
        save(user);
        Blog userBlog = new Blog("userBlog", true, user);
        userBlog.setAvatar(imageService.createBlogAvatar(userBlog.getName()));
        blogRepository.save(userBlog);
        save(new Account("admin", "admin", "ROLE_ADMIN"));
    }

    // More methods

}

这个测试:

@RunWith(MockitoJUnitRunner.class)
public class AccountServiceTest {

    @InjectMocks
    private AccountService accountService = new AccountService();

    @Mock
    private AccountRepository accountRepositoryMock;

    @Test
    public void shouldInitializeWithTwoDemoUsers() throws IOException {
        // act
        accountService.initialize();
        // assert
        verify(accountRepositoryMock, times(2)).save(any(Account.class));
    }

}

为什么当我运行测试时,我得到了这个例外?

shouldInitializeWithTwoDemoUsers(es.udc.fi.dc.fd.account.AccountServiceTest)  Time elapsed: 0.016 sec  <<< ERROR!
java.lang.NullPointerException: null
    at es.udc.fi.dc.fd.account.AccountService.initialize(AccountService.java:45)
    at es.udc.fi.dc.fd.account.AccountServiceTest.shouldInitializeWithTwoDemoUsers(AccountServiceTest.java:42)

使用@PostConstruct注释,它应该注入所有豆子吗?

2 个答案:

答案 0 :(得分:1)

这里几件事。首先@InjectMocks通常会让事情变得更容易,但Mockito不是依赖注入框架,所以它不能保证正常工作。

其次,要使@InjectMocks正常工作,您还需要@Mock所有对象,而不是手动创建您尝试注入的类。我不相信它的情况,但是在mockito的顺序版本中,@Mocks的顺序也很重要。

此代码可能适合您

@RunWith(MockitoJUnitRunner.class)
public class AccountServiceTest {


    @Mock
    private AccountRepository accountRepositoryMock;

    @Mock
    private BlogRepository blogRepository;

    @Mock
    private ImageService imageService;

    @InjectMocks
    private AccountService accountService ;

    @Test
    public void shouldInitializeWithTwoDemoUsers() throws IOException {
        // act
        accountService.initialize();
        // assert
        verify(accountRepositoryMock, times(2)).save(any(Account.class));
    }

}

答案 1 :(得分:1)

您需要模拟测试主题正在使用的所有依赖项。您可能希望在AccountServiceTest类中执行此操作:

@Mock 
private BlogRepository blogRepositoryMock;