Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make <code>DataSource ds</code> a JavaBean property and set its value on your JUnit test. This way you hide the complexity of the JNDI binding and focus your tests only on the business logic. </p> <p>Your controller:</p> <pre><code>@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;} ... } </code></pre> <p>And you test class:</p> <pre><code>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); } } </code></pre> <p>As a side note, following the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">MVC design pattern</a> I would even decouple the controller business logic from the database connection, so no valid connection is needed to execute the unit tests and your focus is entirely on the behavior of your controller.</p> <p>If you are using Spring and want to use all Spring beans within your JUnit class you can always use the <code>@RunWith</code> JUnit annotation.</p> <pre><code>@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); } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload