2013-02-19 2 views
0

내가 JSF 페이지에 내용을 표시이 간단한 CDI 빈을 테스트 : 내가 얻을찾을 수 없습니다 데이터 소스는

public class ZonesTest 
{ 

    @BeforeClass 
    public static void setUpClass() throws Exception 
    { 
     try 
     { 
      // Create initial context 
      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, 
        "org.apache.naming.java.javaURLContextFactory"); 
      System.setProperty(Context.URL_PKG_PREFIXES, 
        "org.apache.naming"); 
      InitialContext ic = new InitialContext(); 

      ic.createSubcontext("java:"); 
      ic.createSubcontext("java:/comp"); 
      ic.createSubcontext("java:/comp/env"); 
      ic.createSubcontext("java:/comp/env/jdbc"); 

      // Construct DataSource 
      OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource(); 
      ds.setURL("jdbc:oracle:thin:@192.168.1.104:1521:oracle"); 
      ds.setUser("admin"); 
      ds.setPassword("qwerty"); 

      ic.bind("java:/comp/env/jdbc/oracle", ds); 
     } 
     catch (NamingException ex) 
     { 
      //Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 

    @Test 
    public void testCountDBRowNum() throws Exception 
    { 

     Zones instance = new Zones(); 
     int rows = instance.countDBRowNum(); 

     System.out.println(rows); 

    } 
} 

: 나는 자바 메소드를 호출이 JUnit 테스트 케이스를 생성

@Named("ZonesController") 
@ViewScoped 
public class Zones implements Serializable 
{ 

    @Resource(name = "jdbc/Oracle") 
    private DataSource ds; 
    ........... 
    public int countDBRowNum() throws Exception 
    { 

     String SqlStatement = null; 

     if (ds == null) 
     { 
      throw new SQLException(); 
     } 

     Connection conn = ds.getConnection(); 
     if (conn == null) 
     { 
      throw new SQLException(); 
     } 

     PreparedStatement ps = null; 
     ResultSet resultSet = null; 
     int count = 0; 

     try 
     { 
      conn.setAutoCommit(false); 
      boolean committed = false; 
      try 
      { 
       SqlStatement = "SELECT COUNT(1) FROM component x, componentstats y WHERE x.componentstatsid = y.componentstatsid AND y.componenttypeid = 1100"; 

       ps = conn.prepareStatement(SqlStatement); 
       resultSet = ps.executeQuery(); 

       if (resultSet.next()) 
       { 
        count = resultSet.getInt(1); 
       } 

       conn.commit(); 
       committed = true; 
      } 
      finally 
      { 
       if (!committed) 
       { 
        conn.rollback(); 
       } 
      } 
     } 
     finally 
     { 
      ps.close(); 
      conn.close(); 
     } 
     // Returns total rows in table. 
     return count; 
     } 
     ............. 
    } 

다음 줄의 오류 :

if (ds == null) 
{ 
    throw new SQLException(); 
} 

이 문제를 어떻게 해결할 수 있습니까? 테스팅 중에 JUnit 테스트의 데이터 소스를 사용하고 싶습니다. 어떻게 든 JUnit 데이터 소스를 사용할 수 있습니까?

답변

1

DataSource ds을 JavaBean 속성으로 만들고 JUnit 테스트에서 값을 설정할 수 있습니다. 이렇게하면 JNDI 바인딩의 복잡성을 숨기고 비즈니스 로직에만 테스트를 집중시킬 수 있습니다.

컨트롤러 :

@Named("ZonesController") 
@ViewScoped 
public class Zones implements Serializable 
{ 

    @Resource(name = "jdbc/Oracle") 
    private DataSource ds; 

    public void setDs(DataSource ds){this.ds=ds;} 
    public DataSource getDs(){return ds;} 

    ... 
} 

그리고 당신은 클래스 테스트 : MVC design pattern 나는 심지어 데이터베이스 연결에서 컨트롤러 비즈니스 로직을 분리 할 다음과 같은 보조 노트로

public class ZonesTest 
{ 
    private static OracleConnectionPoolDataSource ds; 

    @BeforeClass 
    public static void setUpClass() throws Exception 
    { 
     try 
     { 
      // Construct DataSource 
      ds = new OracleConnectionPoolDataSource(); 
      ds.setURL("jdbc:oracle:thin:@192.168.1.104:1521:oracle"); 
      ds.setUser("admin"); 
      ds.setPassword("qwerty"); 
     } 
     catch (NamingException ex) 
     { 
      //Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 

    @Test 
    public void testCountDBRowNum() throws Exception 
    { 

     Zones instance = new Zones(); 
     instance.setDs(ds); 
     int rows = instance.countDBRowNum(); 

     System.out.println(rows); 

    } 
} 

, 그래서 아무 유효 단위 테스트를 실행하려면 연결이 필요하며 컨트롤러의 동작에 전적으로 집중해야합니다.

Spring을 사용하고 있고 JUnit 클래스 내의 모든 스프링 빈을 사용하려는 경우 언제든지 @RunWith JUnit 주석을 사용할 수 있습니다.

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public class ZonesTest 
{ 
    @Autowire 
    Zones zones; 

    // your BeforeClass method here 

    @Test 
    public void testCountDBRowNum() throws Exception 
    { 
     int rows = zones.countDBRowNum(); 

     System.out.println(rows); 

    } 

}

+0

내 코드에 스프링을 사용하지 마십시오. 'SpringJUnit4ClassRunner'를 다른 것으로 대체 할 수 있습니까? –

+0

죄송합니다. Spring MVC를 사용하고 있다고 생각했지만, 제가 언급 한 첫 번째 솔루션을 사용할 수 있습니다. 나는 나의 대답을 편집하여 명확하게했다. – mtrovo

+0

예, 잘 작동합니다. 고맙습니다! –

관련 문제