2016-01-14 120 views
2

我正在使用(EJB,JPA和JPQL)在JAVA EE中創建一個簡單的Web應用程序。我想知道如何使用到的Mockito測試EJB來測試模型。我想嘲笑上下文(數據庫和屬性)在Java EE中的Junit測試(JPA)

我該怎麼辦呢?

@Mock 
private EntityManager mockedEntityManager; 
private static TendererBean tendererBean; 
private static TendererManagerBean tendererManagerBean; 
private static EJBContainer container; 
final Properties p = new Properties(); 
    p.put("jdbc/Mydatabase", "new://Resource?type=DataSource"); 
    p.put("jdbc/Mydatabase.JdbcDriver", "apache_derby_net"); 
    p.put("jdbc/Mydatabase.JdbcUrl", "jdbc:derby://localhost:1527/Mydatabase"); 
    container = EJBContainer.createEJBContainer(p); 
    final Context context = container.getContext(); 
    tendererBean = (TendererBean) context.lookup("java:global/classesTendererManagerBean"); 
+0

我看你想使用derby,這樣的。而不是問「我怎麼做」,說明你與你的嘗試遇到的問題。 – Gimby

+0

是的,問題是我想要爲我的EJB方法(如註冊,更新和刪除)創建測試單元,因爲我應該嘲笑我的上下文,在我的應用程序中使用JSF,EJB和JPA進行持久化 –

+1

你使用CDI?依賴注入使測試/模擬變得更容易。如果你不使用它,那麼我會建議先查看依賴注入。 – Kai

回答

1

應該沒有必要在測試代碼中繞過db屬性。要記住的另一件事:一個單元測試不應該需要一個數據庫連接,因爲那時它比一個單元測試,它還應該嘲笑走的持久性。

EntityManager可以容易地與例如嘲笑的Mockito。此外,你可以模擬一個Query以獲取測試所需的結果。

檢查出Adam Bien's post on Mocking JPA EntityManager and Query如何做到這一點。

2

亞歷克斯是正確的,你不應該需要在單元測試中的數據庫連接(除非你嘗試創建一個集成測試)你可以嘗試像這樣嘲笑他們。代碼可以是凌亂的,希望它有助於

public class ChargeServiceTest { 

@InjectMocks 
private ChargeService chargeService; 

@Mock 
private EntityManager entityManager; 

@Mock 
private Query query; 
@Mock 
private Biller biller; 
@Mock 
private Client client; 

private String expectedSqlQuery1 = "Select count(c) from ClientContractCharge c where c.clientContract.biller =?1 and c.recurringInvoice = true and c.clientContract.client = ?2 and (c.dateCreated >= ?3 or c.dateLastUpdated >= ?3) order by c.dateCreated ASC"; 

@Before 
public void before() { 
    chargeService = new ChargeService(); 
    MockitoAnnotations.initMocks(this); 
} 

@Test 
public void listCountTest1() { 
    when(entityManager.createQuery(expectedSqlQuery1)).thenReturn(query); 
    when(query.getSingleResult()).thenReturn((long) 10); 
    Long count = chargeService.listCount(biller, client); 
    verify(query).setParameter(1, biller); 
    assertEquals(count, Long.valueOf(10)); 
} 
} 

服務類

@Stateless 
@LocalBean public class ChargeService { 
public long listCount(Biller biller, Client client) { 

    StringBuilder s = new StringBuilder(); 
    s.append("Select count(c) from ClientContractCharge c where c.clientContract.biller =?1 and c.recurringInvoice = true "); 
    if (client != null) { 
     s.append("and c.clientContract.client = ?2 "); 
    } 
    s.append(" order by c.dateCreated ASC"); 
    Query q = em.createQuery(s.toString()); 
    q.setParameter(1, biller); 
    if (client != null) { 
     q.setParameter(2, client); 
    } 

    return (long) (Long) q.getSingleResult(); 
}