jUnit单元测试空指针异常而不是自定义异常

时间:2013-11-10 13:43:46

标签: java junit nullpointerexception

这是我的测试:

@Test(expected = NoItemsInStockException.class)
public void cantTakeItemIfNoneInStock() throws NoItemsInStockException {
    User user = new User();
    user.setEmail("example@example.com");
    user.setDebt(0);

    Item item = new Item();
    item.setId(1L);
    item.setPrice(10);
    item.setQuantity(0);

    Mockito.when(userRepository.findByEmail(user.getEmail())).thenReturn(user);
    Mockito.when(itemRepository.findOne(item.getId())).thenReturn(item);

    scanService.takeItem(user.getEmail(), user.getId());
}

这是我的服务提示:

@Override
@Transactional
public void takeItem(final String userEmail, final Long itemId) throws NoItemsInStockException {
    User user = userRepository.findByEmail(userEmail);
    Item item = itemRepository.findOne(itemId);

    if (item.getQuantity() <= 0) {
        throw new NoItemsInStockException("No items left");
    }

    Scan scan = new Scan();
    scan.setDate(new Date());
    scan.setUser(user);
    scan.setItem(item);
    scanRepository.save(scan);

    user.setDebt(user.getDebt() + item.getPrice());
    item.setQuantity(item.getQuantity() - 1);
}

这是我的例外:

public class NoItemsInStockException extends Exception {
    public NoItemsInStockException() {
    }

    public NoItemsInStockException(final String message) {
        super(message);
    }
}

此测试获取NullPointerException而不是NoItemsInStockException,因此失败。我似乎无法弄清楚这里有什么问题?

1 个答案:

答案 0 :(得分:1)

scanService.takeItem(user.getEmail(), user.getId());

你的意思是item.getId(),加上用户没有设置id。