JUnit Test cases failing while running using Maven but works with Eclipse - spring

I have a Junit test case which doesn't work if I run using Maven. But the same test case works when I run using Eclipse.
My Junit class is like this.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/test-config.xml"} )
public class TestDaoImpl {
private final static Logger logger = Logger.getLogger(TestDaoImpl.class);
#Autowired
private MyDaoImpl myDao;
#Test
public void testMyDao() throws Exception {
logger.info("Called testMyDao()================");
// here myDao is null and throwing NullPointerException in sunfire log.
// But this works when I run using Eclipse.
List<MyObj> objList = myDao.getList();
}
#Test
public void testMyCode() throws Exception {
logger.info("Called testMyCode()================");
// this test case works with Maven
List<MyObj> objList = MyClass.getList();
}
}

The sunfire plugin was missing. When added it started working.

Related

How to call a TESTNG class from a Springboot based selenium project

Running Testng class from Springboot application gives an error
I have a Springboot based Selenium Testng project.
When I do a Maven configuration like mvn clean package -Dtests= testng is file name of xml file, it works seemlessly.
Now I have a scenario where I need to get the testsuite name which user likes to test on commandline and use that and run the test suite.
I have the following in the #SpringBootApplication main method. Assuming I get the test suite thru commandline, I have this code, but the springboot servers keeps running in infinite without running the tests.
How could I fix it.
#SpringBootApplication
public class MyAutomationApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(MyAutomationApplication.class, args);
}
public void run(String... args) throws Exception {
System.out.println("Welcome!!");
//assuming i get the InitialLoginTest from commandline, i am passing the CLASS NAME to classes.add(new XmlClass("InitialLoginTest"));
TestNG tng = new TestNG();
XmlSuite suite = new XmlSuite();
suite.setName("Appium Test suite");
XmlTest test = new XmlTest(suite);
test.setName("Sample Test");
List<XmlClass> classes = new ArrayList();
classes.add(new XmlClass("InitialLoginTest"));
test.setXmlClasses(classes);
List<XmlSuite> suites = new ArrayList();
suites.add(suite);
tng.setXmlSuites(suites);
tng.run();
}
}
#SpringBootTest
public class InitialLoginTest {
#Test
void loading() {
System.out.println("In InitialLoginTest!!");
}
}

Spring boot test doesn't Autowire all dependencies

I have a bit of a confusing error in my test scenario.
We want to refactor an Application that is not tested at all. To ensure that we have the same outcame after refactoring I'll write some integration tests for one Controller class.
#RestController
#RequestMapping("/rfq")
public class RfqController {
#Autowired
private RfqRepository rfqRepo;
#Autowired
private RfqDao rfqDao;
...
#PostMapping("/get")
public #ResponseBody BuyerRfqView getRFQ(#RequestBody SingleIdBody body) {
int id = body.getId();
Optional<Rfq> rfq = rfqRepo.getById(id);
...
}
}
In that case I want to test with testcontainers and spring-boot-test everything worked well, containers are up and running and the application starts so far. But the problem is that at runtime the spring-boot-test doesn't Autowire rfqRepo in the class under test. In the Testclass, every single dependency is in the ComponentScan or EntityScan and the repositories are also injected. I have no clue why this is not working. when the test is running I get a Nullpointer Exception by rfqRepo ...
here is the Test class:
#SpringBootTest(classes = RfqController.class, webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
#ComponentScan({...})
#EnableJpaRepositories({...})
#EntityScan({...})
#EnableAutoConfiguration
#ActiveProfiles("local")
#Testcontainers
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class RfqControllerTest {
#Container
private static OracleContainer database = new OracleContainer(
"oracleinanutshell/oracle-xe-11g:latest")
.withExposedPorts(1521, 5500)
.withPassword("...");
#InjectMocks
RfqController rfqController;
#DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", database::getJdbcUrl);
registry.add("spring.datasource.username", database::getUsername);
registry.add("spring.datasource.password", database::getPassword);
}
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
ScriptUtils.runInitScript(new JdbcDatabaseDelegate(database, ""), "ddl.sql");
}
#Test
void testGetRFQ() {
BuyerRfqView result = rfqController.getRFQ(new SingleIdBody(176501));
Assertions.assertEquals(new BuyerRfqView(), result);
}
}
In the SpringBootTest annotation you are only using RfqController. That's the only class then that is available during test.
#SpringBootTest(classes = RfqController.class, webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)
So you have to add all classes that are needed for your tests.

Cannot find spring application class in unit test class

We are in the process of creating from the scratch product with spring webflux. We are writing our unit test cases. Though I can able to get the Spring Application main class in my import, when we run mvn clean install, it is keep on telling that Compilation failure, cannot find class. How we can overcome this?
My project structure is,
Application
-app-web-module
-src/java/com/org/SpringApplicationClass
-pom.xml
-app-web-unitcases
-src/test/com/org/mytestclass
-pom.xml
And my test class is,
#TestPropertySource(properties = "CONFIG_ENVIRONMENT=ci")
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureWebTestClient
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#ContextConfiguration(classes = com.org.MainApplication.class)
public class BaseACTest {
#Autowired
private WebTestClient webTestClient;
#BeforeAll
public void init1() {
MockitoAnnotations.initMocks(this);
}
#BeforeEach
public void init() {
Assertions.assertNotNull(webTestClient);
}
#Test
public void testGetAllAmenities() {
webTestClient.get().uri("/urltobeplaced/1234")
.header("X-Request-ID", "123")
.header("X-Session-ID", "123")
.header("X-Application-ID", "123")
.exchange()
.expectStatus().isOk();
}
}

SpringRunner unable to detect configuration

I have a spring-boot application for which am trying to create unit testcases. Below is the code that I am trying to run, I don't have any configuration file that I have (used only annotations) so the main class that loads all the configuration is ElastSearchBootApplication class. For some reason I see the below error.
#ComponentScan(basePackages = "com.somename")
#SpringBootApplication
#EnableScheduling
public class ElastSearchBootApplication {
private static final Logger LOG = LoggerFactory.getLogger(ElastSearchBootApplication.class);
public static void main(String[] args) {
SpringApplication.run(ElastSearchBootApplication.class, args);
}
#Autowired
private ElastSearchLogLevel logsSearch;
#Scheduled(fixedRate = 120000)
public void scheduledSearchLogs() {
...
Test class :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ElastSearchBootApplication.class)
public class LogSearchTest {
#Mock
private RestHighLevelClient client;
#Mock
private ExecutorService ALERT_POOL;
#Before
public void setUp() throws Exception {
client = mock(RestHighLevelClient.class);
ALERT_POOL = mock(ExecutorService.class);
try {
when(client.search(anyObject())).thenReturn(getResponse());
} catch (Exception e) {
// I see NullPointerException but both the instances are available here
e.printStackTrace();
}
doNothing().when(ALERT_POOL.invokeAll(anyObject()));
}
I see the below error when trying to run the spring-boot test :
org.springframework.boot.test.context.SpringBootTestContextBootstrapper buildDefaultMergedContextConfiguration
INFO: Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.somename.search.LogSearchTest], using SpringBootContextLoader
org.springframework.test.context.support.AbstractContextLoader generateDefaultLocations
INFO: Could not detect default resource locations for test class [com.somename.search.LogSearchTest]: no resource found for suffixes {-context.xml, Context.groovy}.
org.springframework.test.context.support.AnnotationConfigContextLoaderUtils detectDefaultConfigurationClasses
INFO: Could not detect default configuration classes for test class [com.somename.search.LogSearchTest]: LogSearchTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
I see that #SpringBootTest is used for integration tests, so can I use it for unit tests ? If I remove it then I get another set of exception that looks similar though. I would be more interested in running this testcase without SpringBootTest
Why my test case say some configuration is missing. The samples online talk about xml files which I don't have. So what am I missing here ?
Can I dynamically pass the value for fixedRate from Environment and put it like #Scheduled(fixedRate = ${some.value.defined})
UPDATE
I can run the test but without the proper order. Ideally i expect setUp to run first. But its running second. Also the line when(client.search(anyObject())).thenReturn(getResponse()); is failing and i dont get the reason...
You have to add the annotation #ContextConfiguration to your test class to specify configuration file.
#ContextConfiguration(classes = ElastSearchBootApplication.class)
Try this:
#RunWith(SpringRunner.class)
#SpringBootTest
public class LogSearchTest {
#MockBean
private RestHighLevelClient client;
#MockBean
private ExecutorService ALERT_POOL;
#Before
public void setUp() throws Exception {
try {
when(client.search(anyObject())).thenReturn(getResponse());
} catch (Exception e) {
// I see NullPointerException but both the instances are available here
e.printStackTrace();
}
doNothing().when(ALERT_POOL.invokeAll(anyObject()));
}

spring-boot: Application loads but tests fail

I am experiencing rather strange thing when using Spring Boot. Lets get with it.
I have an app which, when ran from spring-boot:run, loads perfectly fine and I can use my server. However, if I try to run tests (either via launching test from IntelliJ or via surefire plugin) context fails to load.
Issue lies within this class (only relevant part shown):
#RestController
#RequestMapping(
value = "/sa/revisions/"
)
#SuppressWarnings("unchecked")
class RevisionController {
#Autowired
// cant autowire this field
private RepositoryEntityLinks repositoryEntityLinks = null;
/* omitted */
}
And here is my main class:
#EnableAsync
#EnableCaching
#EnableAutoConfiguration
#EnableConfigurationProperties
#Import({
SecurityConfiguration.class,
DataConfiguration.class,
RestConfiguration.class
})
public class SpringAtomApplication {
#Autowired
private DataLoaderManager dataLoaderManager = null;
public static void main(String[] args) {
SpringApplication.run(SpringAtomApplication.class, args);
}
#Bean
public CacheManager cacheManager() {
final GuavaCacheManager manager = new GuavaCacheManager();
manager.setAllowNullValues(false);
return manager;
}
#PostConstruct
private void doPostConstruct() {
this.dataLoaderManager.doLoad();
}
}
As I said, application loads without an issue when ran normally, however when it comes to this simple test, everything falls apart:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = SpringAtomApplication.class)
public class SpringAtomApplicationTests {
#Test
public void contextLoads() {
}
}
Would appreciate any suggestion, because I'd love to start with testing it.
You should set SpringApplicationContextLoader in your test class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(
classes = SpringAtomApplication.class,
loader = SpringApplicationContextLoader.class)
public class SpringAtomApplicationTests {
#Test
public void contextLoads() {
}
}
With that you can test non-web features (like a repository or a service) or start an fully-configured embedded servlet container and run your tests using MockMvc.
Reference: http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/SpringApplicationContextLoader.html

Resources