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

ここに私のサービスの実装があります:

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

このテストは NoItemsInStockException ではなく NullPointerException を取得するため、失敗します。ここで何が間違っているのかわかりませんか?

4

1 に答える 1

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

あなたはitem.getId()を意味し、さらにユーザーにはIDが設定されていません。

于 2013-11-10T13:47:03.547 に答える