Fix gradient function and add test

Fix #5320