Mockito例外を取得しています:チェックされた例外はこのメソッドでは無効です質問する

Mockito例外を取得しています:チェックされた例外はこのメソッドでは無効です質問する

私はテストしようとしている方法を持っています

public List<User> getUsers(String state) {

        LOG.debug("Executing getUsers");

        LOG.info("Fetching users from " + state);
        List<User> users = null;
        try {
            users = userRepo.findByState(state);
            LOG.info("Fetched: " + mapper.writeValueAsString(users));
        }catch (Exception e) {
            LOG.info("Exception occurred while trying to fetch users");
            LOG.debug(e.toString());
            throw new GenericException("FETCH_REQUEST_ERR_002", e.getMessage(), "Error processing fetch request");
        }
        return users;
    }

以下は私のテストコードです:

@InjectMocks
    private DataFetchService dataFetchService;

    @Mock
    private UserRepository userRepository;

@Test
    public void getUsersTest_exception() {
        when(userRepository.findByState("Karnataka")).thenThrow(new Exception("Exception"));
        try {
            dataFetchService.getUsers("Karnataka");
        }catch (Exception e) {
            assertEquals("Exception", e.getMessage());
    }
    }

以下は私の UserRepository インターフェースです。

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {

public List<User> findByState(String state);
}

テストを Junit テストとして実行すると、次のエラーが発生します。

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception: Exception occurred

これを解決する方法をご存知ですか? よろしくお願いします。

ベストアンサー1

これを使用RuntimeExceptionまたはサブクラス化する必要があります。メソッドはチェック例外を宣言する必要があります (例: findByState(String state) throws IOException;)。それ以外の場合は、次を使用しますRuntimeException

 when(userRepository.findByState("Karnataka"))
       .thenThrow(new RuntimeException("Exception"));

おすすめ記事