2

I thought this would be a trivial matter, but I can't seem to find a method similar to class_exists in Java. I'm writing a test to verify that a class name is defined. How can I replicate this in Java with jUnit?

<?php

$this->assertTrue(class_exists('Car'), 'Should have a class called "Car"');

TestCar.java

import org.junit.Assert;

import org.junit.Test;

public class TestCar {

    @Test
    public void testCarExists() {
            try {
                Class.forName("Car");
            } catch(ClassNotFoundException e) {
                Assert.fail("Should create a class called 'Car'.");
            }
     }
}

Car.java

public class Car {
    // just enough :-)
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
theGrayFox
  • 921
  • 1
  • 10
  • 22

1 Answers1

5

One advantage of Java is that you have a compiler, so usually this is a non-issue. If you compile your code properly and then, for some reason, drop a required jar file from the runtime environment, you'll get a java.lang.ClassNotFoundException, so that should be enough.

If you want to be super-extra-safe, you could try calling Class.forName:

@Test
public void testClassExists {
    try {
        Class.forName("org.mypackage.Car");
    } catch (ClassNotFoundException e) {
        Assert.fail("should have a class called Car");
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • This gives me a good enough idea to implement something similar. I appreciate the help! – theGrayFox Jan 30 '14 at 17:34
  • Quick question, if my class is specified in a default package, what would the file path be? I've been trying to figure this out for awhile now. I've specified ```Class.forName("Car");``` but this test is still failing and not finding the class. – theGrayFox Jan 30 '14 at 19:12
  • `Class.forName("Car")` should work just fine. Can you edit your original post (or better yet - open a new question) with the full stacktrace and class definition? – Mureinik Jan 30 '14 at 19:19
  • I've edited it. Note, both files are located in the default package. I can't see why jUnit giving me an initialization error when I've defined the class. – theGrayFox Jan 30 '14 at 19:33