简体   繁体   中英

Using jUnit to test a class / object which is not created yet

I am working on a program that will be a sort of game for beginner programmers. I intend to provide a field where the users can write code as required (method, class... ). When the user wants to submit the code, I will copy the content of the text field into a .java file, call the compiler to compile this class, and then I want to test whether the code works okay using jUnit.

Well, I know that jUnit is used for development purposes, but I think it could be very useful implementing it in this case as well.

Now the problem is that when I will need to compile my program, the class which will supposedly be tested (the user's code) is not going to be there. So I cannot just call

assertEquals( "Wrong sum", 6, Foo.sum( 4, 2));

because it will not know what Foo class is, since it will never be there at the time of compilatoin - before the user runs the application and starts coding.

I thought I could create a dummy class, just for the sake of compilation, but then when I will need the real thing, I won't be able to replace the file or write another file like Foo2.java, because the FooTest.java will only operate with object Foo....

I would really appreciate your suggestions guys!!! What can I do to deal with this situation?

Thanks :)

Two options:

  • Have the user implement an interface and use the interface in the JUnit
  • Use reflection to get the public method from the class and call it.

Reflection Version:

If you have an instance of the class you want to test (could be of type Object ), use getClass to get the Class object. Then use getDeclaredMethods to get a list of the Methods . Iterate the Methods till you find the one you want to test (hopefully the only public method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM