Skip to content

Instantly share code, notes, and snippets.

@cuongld2
Created Dec 4, 2021
Embed
What would you like to do?
Unit test examle
package donald.apiwithspringboot;
import donald.apiwithspringboot.controller.MovieController;
import donald.apiwithspringboot.model.Movie;
import donald.apiwithspringboot.repository.MovieRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Optional;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MovieTest {
@MockBean(name = "movieRepository")
MovieRepository movieRepository;
@Autowired
private MovieController movieController;
@Test
public void blogById () {
Movie movie = new Movie();
movie.setTitle("Testing");
movie.setContent("A movie about Testing");
movie.setId(1);
movie.setAuthor("Donald");
Mockito.when(movieRepository.findById(movie.getId())).thenReturn(Optional.of(movie));
Optional<Movie> blog_service_abc = Optional.ofNullable(movieController.show("1"));
assertThat(movie.getTitle()).isEqualTo(blog_service_abc.get().getTitle());
assertTrue(movie.getContent().matches(".*movie about.*"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment