unit-testing-in-android-course icon indicating copy to clipboard operation
unit-testing-in-android-course copied to clipboard

Test Cases in Solution of Exercise 11 are not sufficiently reliable

Open tai-nguyen2112 opened this issue 1 year ago • 0 comments

Test Cases in Solution of Exercise 11 are not sufficiently reliable as they let my wrong implementation pass My implementation only uses one variable for caching. Please check

`public class FetchQuestionDetailsUseCase extends BaseObservable<FetchQuestionDetailsUseCase.Listener> {

public interface Listener {
    void onQuestionDetailsFetched(QuestionDetails questionDetails);

    void onQuestionDetailsFetchFailed();
}

private final int CACHING_TIME_OUT = 60000;
private final FetchQuestionDetailsEndpoint mFetchQuestionDetailsEndpoint;
private final TimeProvider mTimeProvider;

private final Map<String, QuestionDetails> cachedValueMap = new HashMap<>();

private long lastCachedTimestamp;

public FetchQuestionDetailsUseCase(FetchQuestionDetailsEndpoint fetchQuestionDetailsEndpoint,
                                   TimeProvider timeProvider) {
    mFetchQuestionDetailsEndpoint = fetchQuestionDetailsEndpoint;
    mTimeProvider = timeProvider;
}

public void fetchQuestionDetailsAndNotify(String questionId) {
    QuestionDetails cachedData = getValidCachedData(questionId);
    if (cachedData != null) {
        notifySuccess(cachedData);
    } else {
        mFetchQuestionDetailsEndpoint.fetchQuestionDetails(questionId, new FetchQuestionDetailsEndpoint.Listener() {
            @Override
            public void onQuestionDetailsFetched(QuestionSchema question) {
                lastCachedTimestamp = mTimeProvider.getCurrentTimestamp();
                QuestionDetails questionDetails = schemaToQuestionDetails(question);
                cachedValueMap.put(questionId, questionDetails);
                notifySuccess(questionDetails);
            }

            @Override
            public void onQuestionDetailsFetchFailed() {
                notifyFailure();
            }
        });
    }
}

private QuestionDetails getValidCachedData(String questionId) {
    QuestionDetails result = cachedValueMap.get(questionId);
    if (result != null &&
            mTimeProvider.getCurrentTimestamp() < lastCachedTimestamp + CACHING_TIME_OUT)
        return result;

    return null;
}

private void notifyFailure() {
    for (Listener listener : getListeners()) {
        listener.onQuestionDetailsFetchFailed();
    }
}

private void notifySuccess(QuestionDetails question) {
    for (Listener listener : getListeners()) {
        listener.onQuestionDetailsFetched(question);
    }
}

@NonNull
private static QuestionDetails schemaToQuestionDetails(QuestionSchema questionSchema) {
    return new QuestionDetails(
            questionSchema.getId(),
            questionSchema.getTitle(),
            questionSchema.getBody()
    );
}

} `

tai-nguyen2112 avatar Dec 08 '23 09:12 tai-nguyen2112