0

这是我的测试:

@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());
}

这是我的服务 impl:

@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,因此失败。我似乎无法弄清楚这里有什么问题?

4

1 回答 1

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

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

于 2013-11-10T13:47:03.547 回答