简体   繁体   中英

How to write Junit test cases for spring boot application?

I have to write some junit test cases to check entity. I'm using postgres as my database.

My entity class

@Entity
@Table(name = "display")
public class Display {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String group;

public Display() {

}
public Display(Long id, String title, String grp) {
    this.id = id;
    this.title= title;  
    this.group= grp;
}

public void setId(Long id) {
    this.id = id;
}

public Long getId() {
    return this.id;
}

public void setGroup(String id) {
    this.group = id;
}

public String getGroup() {
    return this.group;
}

public void settitle(String title) {
    this.title = title;
}

public String gettitle() {
    return this.title;
}

}

My repository

@Repository
public interface DisplayRepository extends CrudRepository<Display, Long> {

}

Interface

public interface IDisplayService {
    List<Display> findAll();
}

Service class

@Service
public class DisplayService implements IDisplayService {
    @Autowired
    private DisplayRepository repository;

@Override
public List<Display> findAll() {
    List<Display> d = (List<Display>) repository.findAll();
    return d;
}
}

I tried writing junit test cases but I get Could'nt load Application. Whats the right way to write junit test cases for this?

This is the test case I wrote for service

folder: test/java/example/demo/Test.java

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource("classpath:conn.properties")

public class DisplayServiceTest {


@Value("${id}")
private String value;


@Mock
private DisplayRepository DisplayReps;

@InjectMocks
private DisplayService DisplayService;

@Test
public void whenFindAll_thenReturnProductList() {

Menu m = new Menu()
m.setId(value);

    List<Display> expectedDisplay = Arrays.asList(m);
    doReturn(expectedDisplay).when(DisplayReps).findAll();
    List<Display> actualDisplay = DisplayService.findAll();
    assertThat(actualDisplay).isEqualTo(expectedDisplay);
}

in test/java/example/demo/resources conn.properties id=2

Its returning 0 for value Whats the issue? Thanks

I have managed to make your code to work. I will post only the changed classes:

The interface:

public interface DisplayRepository extends CrudRepository<Display, Long> {

   Optional<Display> findByTitle(String name);
}

The test class:

@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
@DataJpaTest
public class DisplayRepositoryTest {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private DisplayRepository productRespository;

@Before()
public void setUp(){

    Display m = new Display();
    // m.setId(2L); // The ID is autogenerated; can retrieve it from the persistAndFlush result
    m.setCategory("Group1");
    m.setTitle("Product2");

    testEntityManager.persistAndFlush(m);
}

@Test
public void whenFindByName_thenReturnProduct() {
    // when
    Display product = productRespository.findByTitle("Product2").orElseThrow(() -> new RuntimeException("Product not found"));

    // then
    assertThat(product.getTitle()).isEqualTo("Product2");
}

@Test
public void whenFindAll_thenReturnProductList() {
    // when
    List<Display> products = (List<Display>) productRespository.findAll();

    // then
    assertThat(products).hasSize(1);
}
}

When trying to run the code you provided, there were a few issues:

  • you were using the reserved word group as a field in the Display class. Because of this, Hibernate couldn't create the table, so I renamed it to category.
  • there was a compilation issue because the method findByName wasn't defined in the repository; also, there was no field name in the Display class to which the mapping to be made; because of this, I've added the method findByTitle because it's an existing field and it seemed to match the value you queried in the test method.
  • because the ID field is autogenerated, the test setup() failed when persisting the Display.

If you want to use @Mock for mocking classes, you must call:

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

You can then mock responses as usual: Mockito.when(DisplayReps.findByTitle("A")).thenReturn(Optional.of(new Display(2L, "ALFA", "GRP1")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM