Is there a way to get a class that extends AbstractTransactionalJUnit4SpringContexts to play nicely with JUnit's own @RunWith(Parameterized.class), so that fields marked as Autowired get wired in properly?
@RunWith(Parameterized.class)
public class Foo extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired private Bar bar
@Parameters public static Collection<Object[]> data() {
// return parameters, following pattern in
// http://junit.org/apidocs/org/junit/runners/Parameterized.html
}
@Test public void someTest(){
bar.baz() //NullPointerException
}
}
if you are writing unit tests a recommend you use @Mock and @InjectMocks . But if you really want test all the flow and need to inject classes, you can @RunWith(SpringJUnit4ClassRunner. class) and @Autowired your classes.
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
Create a Controller Now lets add our class in our Controller. We have create a simple Controller that has the variable userService that has @autowired annotation. For simplicity, we just made the request method to be GET and that the request parameters are included in the URL.
@SpringJUnitConfig is a composed annotation that combines @ExtendWith(SpringExtension. class) from JUnit Jupiter with @ContextConfiguration from the Spring TestContext Framework. As of Spring Framework 5.3, this annotation will effectively be inherited from an enclosing test class by default.
See http://jira.springframework.org/browse/SPR-5292 There is a solution.
You can use a TestContextManager from Spring. In this example, I'm using Theories instead of Parameterized.
@RunWith(Theories.class)
@ContextConfiguration(locations = "classpath:/spring-context.xml")
public class SeleniumCase {
@DataPoints
public static WebDriver[] drivers() {
return new WebDriver[] { firefoxDriver, internetExplorerDriver };
}
private TestContextManager testContextManager;
@Autowired
SomethingDao dao;
private static FirefoxDriver firefoxDriver = new FirefoxDriver();
private static InternetExplorerDriver internetExplorerDriver = new InternetExplorerDriver();
@AfterClass
public static void tearDown() {
firefoxDriver.close();
internetExplorerDriver.close();
}
@Before
public void setUpStringContext() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}
@Theory
public void testWork(WebDriver driver) {
assertNotNull(driver);
assertNotNull(dao);
}
}
I found this solution here : How to do Parameterized/Theories tests with Spring
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With