Home > AI > Backend > SpringBoot > Junit >

Junit Test Example

Step 1: install dependency

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test-autoconfigure</artifactId>
</dependency>

Step 2: TutorialRepositoryTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class TutorialRepositoryTest {

    @Autowired
    TutorialRepository tutorialRepository;

    @Test
    public void testGetAllTutorials() {
        tutorialRepository.deleteAll();
        Tutorial t1 = new Tutorial();
        t1.setId("1");
        t1.setTitle("hello");
        t1.setDescription("beautiful");
        tutorialRepository.save(t1);
    }

    @Test
    public void testGetTutorialById() {

    }

    @Test
    public void testCreateTutorial() {

        tutorialRepository.deleteAll();
        Tutorial t1 = new Tutorial();
        t1.setId("1");
        t1.setTitle("hello");
        t1.setDescription("beautiful");
        tutorialRepository.save(t1);

        List<Tutorial> ts = tutorialRepository.findAll();
        assertEquals(ts.size(), 1);

        Optional<Tutorial> t2 = tutorialRepository.findById("1");
        assertEquals(t2.get().getTitle(), "hello");
        assertEquals(t2.get().getDescription(), "beautiful");
    }

    @Test
    public void testUpdateTutorial() {

    }


    @Test
    public void testDeleteTutorial() {

    }

    @Test
    public void testDeleteAllTutorials() {

    }

    @Test
    public void testFindByPublished() {

    }

}

Tutorial.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "tutorials")
public class Tutorial {
    @Id
    private String id;
    private String title;
    private String description;
    private boolean published;
}

TutorialRepository.java

public interface TutorialRepository extends MongoRepository<Tutorial, String> {
    List<Tutorial> findByTitle(String title);
    List<Tutorial> findByPublished(boolean published);
}

Leave a Reply