【发布时间】:2016-10-27 07:07:45
【问题描述】:
我正在使用 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吧?
【问题讨论】:
-
@Matt1776 如果我删除出现异常的行,我会在此行中得到空指针:
blogRepository.save(userBlog);。我测试 userBlog 是否为 null 而不是,所以我现在很困惑... -
错误出现在第 45 行,这不是您放在这里的代码的一部分。你能粘贴那部分吗?
-
嗨@AdityaK,错误来自
shouldInitializeWithTwoDemoUsers方法,这是我在调用AccountService 的initialize()方法时输入的代码的一部分。 -
我认为你应该在你的测试类中使用@Mock BlogRepository blogRepository?你试过了吗?
-
那是错误!我没有模拟我的
BlogRepository存储库,所以现在测试通过了,非常感谢@AdityaK!