我正在使用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批注应该已经注入了所有bean吗?

最佳答案

这里的东西很少。首先,@InjectMocks通常使事情变得容易,但是Mockito不是依赖注入框架,因此不能保证其正常工作。

其次,为了使@InjectMocks正常工作,您还需要同时@Mock所有对象,而不是手动创建要注入的类。我不相信这种情况了,但是在模仿版本的顺序中,@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));
    }

}

07-26 04:38