I would like to develop nested test classes with JUnit 5 (Eclipse 4.7.2, as Maven-Project).
I have the following example test class:
package Main.Demo;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import XYZQA.StdLibCore.jUnit.ClientDescriptionParameterResolver;
#RunWith(JUnitPlatform.class) //is necessary to run jUnit 5 tests with non-junit5-implemented IDEs
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#ExtendWith(ClientDescriptionParameterResolver.class)
#DisplayName("Test class 7")
class T7
{
#BeforeAll
static void setUpBeforeClass() throws Exception
{
}
#AfterAll
static void tearDownAfterClass() throws Exception
{
}
#BeforeEach
void setUp() throws Exception
{
}
#AfterEach
void tearDown() throws Exception
{
}
#Nested
#DisplayName("First Group")
class T71
{
#Test
#DisplayName("Test a")
void test()
{
//fail("Not yet implemented");
}
}
#Nested
#DisplayName("Second Group")
class T72
{
#Test
#DisplayName("Test b")
void test()
{
//fail("Not yet implemented");
}
}
}
Question:
Are there possibilities to outsource the two classes T71 and T72 in separate files? Because I need a better organization of the test classes hierarchy (goal: not all nested sub test classes in one file).
By definition, #Nested test classes are required to be "non-static nested classes" (i.e., inner classes).
Are there possibilities to outsource the two classes T71 and T72 in separate files? Because I need a better organization of the test classes hierarchy (goal: not all nested sub test classes in one file).
Yes, you can of course structure your tests classes as you like.
If you don't want nested test classes, just make them top-level classes and/or create a test class hierarchy (via extends), but if you do that you obviously will not be able to benefit from the shared state feature of #Nested classes.
In the end, the way you structure your tests really just depends on your needs.
Related
Im using wildfly 9.0 to deploy my war file. I have java LocalDateTime, Java Money types defined in my REST GET endpoints.
When i deploy my war file, i get following error[1]. Based on this answer [2] I have written "ParamConverterProvider" implementations for both types.
It was working fine( I haven't seen same issue again till now) and now i get same issue.
Any clue?
[1]
Caused by: java.lang.RuntimeException: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.QueryParam(\"totalMoneyVolumeForPeriod\") on public javax.ws.rs.core.Response com.test.rest.StockEndpoint.getItems(java.lang.Integer,java.lang.Integer,java.lang.String,java.lang.String,java.lang.Long,org.javamoney.moneta.Money,java.util.Set,java.lang.String) for basetype: org.javamoney.moneta.Money"}}}}
[2]
jaxrs could not find my custom (de)serializers for joda.money type
Sample code
package com.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import javax.money.Monetary;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import org.javamoney.moneta.Money;
#Provider
public class MoneyConverterProvider implements ParamConverterProvider {
private final MoneyConverter converter = new MoneyConverter();
#Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (!rawType.equals(Money.class)) return null;
return (ParamConverter<T>) converter;
}
public class MoneyConverter implements ParamConverter<Money> {
public Money fromString(String value) {
if (value == null ||value.isEmpty()) return null; // change this for production
return Money.of(new BigDecimal(value), Monetary.getCurrency("AUD"));
}
public String toString(Money value) {
if (value == null) return "";
return value.toString(); // change this for production
}
}
}
Application claas
package com.test;
import javax.ws.rs.core.Application;
import com.test.autogen*;
import io.swagger.jaxrs.config.BeanConfig;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
#ApplicationPath("/rest")
public class RestApplication extends Application {
public RestApplication() {
BeanConfig beanConfig = new BeanConfig();
//beanConfig.setVersion("1.0");
beanConfig.setSchemes(new String[] { "http" });
beanConfig.setTitle("My API");
beanConfig.setBasePath("/rest");
beanConfig.setResourcePackage("com.test.autogen");
beanConfig.setScan(true);
}
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>();
set.add(EmailEndpoint.class);
set.add(StockEndpoint.class);
set.add(io.swagger.jaxrs.listing.ApiListingResource.class);
set.add(io.swagger.jaxrs.listing.SwaggerSerializers.class);
return set;
}
}
When you are using classpath scanning, JAX-RS components annotated with #Path or #Provider will get picked up and registered. There are a couple way to use classpath scanning. The most common way is to just have an empty Application class annotated with #ApplicationPath
#ApplicationPath("/api")
public class MyApplication extends Application {}
This is enough for a JAX-RS application to be loaded, and to have the application's classpath scanned to components to register.
But, per the specification, once we override any of the Set<Object> getSingletons or Set<Class> getClasses methods of the Application class, and return a non-empty set, this automatically disables classpath scanning, as it is assumed we want to register everything ourselves.
So in previous cases, you were probably just using classpath scanning. In this case, you need to explicitly add the provider to the set of classes in your getClasses method, since you overrode the method to add other component classes.
Is the order of the test methods in a Test Suite by JUnit4Spring reliable?
Otherwise, is there anyway to enforce the order?
Thank you a lot.
The SpringJUnit4ClassRunner is great!
If you are using JUnit 4.11, you can also use the #FixMethodOrder annotation
See example:
import org.junit.runners.MethodSorters;
import org.junit.FixMethodOrder;
import org.junit.Test;
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
#Test
public void firstTest() {
System.out.println("first");
}
#Test
public void secondTest() {
System.out.println("second");
}
}
What is the difference between using JUnit #BeforeClass and the Spring #TestExecutionListener beforeTestClass(TestContext testContext) "hook"? If there is a difference, which one to use under which circumstances?
Maven Dependencies:
spring-core:3.0.6.RELEASE
spring-context:3.0.6.RELEASE
spring-test:3.0.6.RELEASE
spring-data-commons-core:1.2.0.M1
spring-data-mongodb:1.0.0.M4
mongo-java-driver:2.7.3
junit:4.9
cglib:2.2
Using JUnit #BeforeClass annotation:
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
#ContextConfiguration(locations = { "classpath:test-config.xml" })
public class TestNothing extends AbstractJUnit4SpringContextTests {
#Autowired
PersonRepository repo;
#BeforeClass
public static void runBefore() {
System.out.println("#BeforeClass: set up.");
}
#Test
public void testInit() {
Assert.assertTrue(repo.findAll().size() == 0 );
}
}
=> #BeforeClass: set up.
=> Process finished with exit code 0
Using the Spring hook:
(1) Override beforeTestClass(TextContext testContext):
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
public class BeforeClassHook extends AbstractTestExecutionListener {
public BeforeClassHook() { }
#Override
public void beforeTestClass(TestContext testContext) {
System.out.println("BeforeClassHook.beforeTestClass(): set up.");
}
}
(2) Use #TestExecutionListeners annotation:
import org.springframework.test.context.TestExecutionListeners;
// other imports are the same
#ContextConfiguration(locations = { "classpath:test-config.xml" })
#TestExecutionListeners(BeforeClassHook.class)
public class TestNothing extends AbstractJUnit4SpringContextTests {
#Autowired
PersonRepository repo;
#Test
public void testInit() {
Assert.assertTrue(repo.findAll().size() == 0 );
}
}
=> BeforeClassHook.beforeTestClass(): set up.
=> Process finished with exit code 0
TestExecutionListeners are a way to externalize reusable code that instruments your tests.
As such, if you implement a TestExecutionListener you can reuse it across test class hierarchies and potentially across projects, depending on your needs.
On the flip side, a #BeforeClass method can naturally only be used within a single test class hierarchy.
Note, however, that JUnit also supports Rules: if you implement org.junit.rules.TestRule you can declare it as a #ClassRule to achieve the same thing... with the added benefit that a JUnit Rule can be reused just like a Spring TestExecutionListener.
So it really depends on your use case. If you only need to use the "before class" functionality in a single test class or a single test class hierarchy, then you'd be better off going the simple route of just implementing a #BeforeClass method. However, if you foresee that you will need the "before class" functionality in different test class hierarchies or across projects, you should consider implementing a custom TestExecutionListener or JUnit Rule.
The benefit of a Spring TestExecutionListener over a JUnit Rule is that a TestExecutionListener has access to the TestContext and therefore access to the Spring ApplicationContext which a JUnit Rule would not have access to. Furthermore, a TestExecutionListener can be automatically discovered and ordered.
Related Resources:
SPR-8854
Regards,
Sam (author of the Spring TestContext Framework)
The first solution with #BeforeClass doesn't have application context loaded. I did exteneded AbstractJUnit4SpringContextTests and defined #ContextConfiguration.
I think listner is the only way to get context loaded before #beforeclass method. Or even better extending SpringJUnit4ClassRunner class as mentioned here
I want to run the same JUnit tests for different interface implementations. I found a nice solution with the #Parameter option:
public class InterfaceTest{
MyInterface interface;
public InterfaceTest(MyInterface interface) {
this.interface = interface;
}
#Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}
This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:
#Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}
#Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}
If the isEmptyTest is run after the insertTest it fails.
Is there an option to run automatically each testcase with a new instance of an implementation?
BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.
Here is another approach with the Template Method pattern:
The interface-oriented tests go into the base class:
public abstract class MyInterfaceTest {
private MyInterface myInterface;
protected abstract MyInterface makeContractSubject();
#Before
public void setUp() {
myInterface = makeContractSubject();
}
#Test
public void isEmptyTest(){
assertTrue(myInterface.isEmpty());
}
#Test
public void insertTest(){
myInterface.insert(new Object());
assertFalse(myInterface.isEmpty());
}
}
For each concrete class, define a concrete test class:
public class GoodInterfaceImplTest extends MyInterfaceTest {
#Override
protected MyInterface makeContractSubject() {
// initialize new GoodInterfaceImpl
// insert proper stubs
return ...;
}
#Test
public void additionalImplementationSpecificStuff() {
...
}
}
A slight advantage over #Parameter is that you get the name of the concrete test class reported when a test fails, so you know right away which implementation failed.
Btw, in order for this approach to work at all, the interface must be designed in a way which allows testing by the interface methods only. This implies state-based testing -- you cannot verify mocks in the base test class. If you need to verify mocks in implementation-specific tests, these tests must go into the concrete test classes.
Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters() return a list of factories.
Then you can invoke the factory in a #Before annotated method to get a new instance of your actual class under test for each test method run.
Just in case somebody reaches here(like I did), looking for testing multiple implementations of the same interface in .net you could see one of the approaches that I was using in one of the projects here
Below is what we are following in short
The same test project dll is run twice using vstest.console, by setting an environment variable. Inside the test, (either in the assembly initialize or test initialize) register the appropriate implementations into a IoC container, based on the environment variable value.
In Junit 5 you could do:
#ParameterizedTest
#MethodSource("myInterfaceProvider")
void test(MyInterface myInterface) {}
static Stream<MyInterface> myInterfaceProvider() {
return Stream.of(new ImplA(), new ImplB());
}
interface MyInterface {}
static class ImplA implements MyInterface {}
static class ImplB implements MyInterface {}
I have a JUnit test that I run on one class, but I recently wrote an emulated version for GWT. Since the specification is the same, I would like to use the same test case, but I want it to run in the GWT environment, which would typically be accomplished by extending GWTTestCase.
I really want to avoid any copy/paste nonsense, because there are likely to be added tests in the future, which I should not be burdened with copying later.
How can I import/inherit my standard unit test to be run as either a regular test case or a GWT test case?
I have found the solution to this problem.
If you extend the original test with GWTTestCase, you can override getModuleName to return null. This tells GWTTestCase to run as a normal pure java test (no translation at all).
You can then extend this test case with one that overrides getModuleName to return a module name, and the same tests will be run with translation.
Basically:
public class RegularTest extends GWTTestCase {
#Override
public String getModuleName() { return null; }
public void testIt() {...}
}
...and the GWT version...
public class GwtTest extends RegularTest {
#Override
public String getModuleName() { return "some.module"; }
}
The downside to this is that it forces you to use JUnit3 style tests, which I find a little annoying, but it beats the alternative.
I think there is no easy way .. But you can extract an interface of your junit test, gwt test case and junit test case implements this interface. You can create a third class for implementation, all test call methods of gwt test case and junit test are delegated to this implementation class.
public interface IRegularTest {
public void testSomething();
public void testSomething2();
}
public class RegularTestImpl implements IRegularTest {
public void testSomething(){
// actual test code
}
public void testSomething2(){
// actual test code
}
}
public class RegularTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}
public class GwtTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}