Bravo
Bravo

Reputation: 1139

Spring unit testing, how to check that methods store info in db?

I am new to spring and currently I am trying to perform unit testing for my project. I have configured spring with hibernate and now I want to check if methods of the created classes work. For instance, let's say I have:

@Entity
@Table(name = "product")
public class DefaultProduct implements Product, Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name = "product_name", nullable = false)
private String productName;

@Column(name = "product_price", nullable = false)
private double productPrice;

@Column(name = "product_quantity", nullable = false)
private int productQuantity;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
private Set<DefaultAccount> account;

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public double getProductPrice() {
    return productPrice;
}

public void setProductPrice(double productPrice) {
    this.productPrice = productPrice;
}

public int getProductQuantity() {
    return productQuantity;
}

public void setProductQuantity(int productQuantity) {
    this.productQuantity = productQuantity;
}

public Set<DefaultAccount> getAccount() {
    return account;
}

public void setAccount(Set<DefaultAccount> account) {
    this.account = account;
}

How to correctly test these methods? What is the best option? I am used to assertTrue and assertFalse in JUnit testing, but I am afraid this won't be a good option in my case. Thank you.

Upvotes: 0

Views: 74

Answers (2)

Somaiah Kumbera
Somaiah Kumbera

Reputation: 7489

@Vaelyr is correct. You should be integration testing the DAO and service layer objects, i.e the ones that are actually putting the code into the DB.

You can test your DAO object with

import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context.xml"})
public class DaoIntegrationTest {

@Autowired
TheDaoObject theDaoObject;

@Test
public void testAdd() {
    theDaoObject.addSomething("one", "two");
}

@Test
public void testGet() {
    List<Something> somethingList = theDaoObject.getSomethingById("one");
    Assert.assertTrue("Something found", somethingList.size() > 0);
}
}

Upvotes: 1

DavidW88
DavidW88

Reputation: 56

A unit test should not be hitting the database. Unit testing a POJO should be at the lowest level of modularity.

Upvotes: 1

Related Questions