Arquillan EJB3 unit test - java.lang.ClassNotFoundException - unit-testing

I'm running an EJB unit test with Arquillian but I receive
java.lang.ClassNotFoundException: org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder
my test class is this
#RunWith(Arquillian.class)
public class EjbTest {
#Inject
private RepAlertManagerImpl ejb;
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "foo.jar")
.addClasses(RepAlertManagerImpl.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
#Test
public void testEjb() throws IOException, SQLException {
try
{
List<Long> result = ejb.doSomething("ENTRATE");
for(Long temp:result){
System.out.println(temp);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
the jar I use for this client are
arquillian-container-test-api-1.1.7.Final;
arquillian-junit-core-1.1.7.Final;
junit-4.12

I finally solved with gradle.
My build.gradle contains:
compile 'junit:junit:4.8.2'
compile 'org.jboss.arquillian.junit:arquillian-junit-container:1.1.7.Final'
just type gradle eclipse from build.gradle file dir (project directory)

Related

Unit Test Vertx AsyncHandler with Mockito

I am trying yo unit test my method which internally calls DB which I am trying to mock and want to return the response but getting an error.
public void processAlert(JsonObject requestInput, Handler<AsyncResult<JsonObject>> handler) {
JsonObject jobInput = new JsonObject().put("requestInput", requestInput);
dbService.saveJobDetails(jobInput, readyHandler -> {
if (readyHandler.succeeded()) {
handler.handle(Future.succeededFuture(readyHandler.result()));
} else {
handler.handle(Future.failedFuture(readyHandler.cause()));
}
});
}
Test code for mocking the dbService
#Mock
DBService dbService;
#Captor
private ArgumentCaptor<Handler<AsyncResult<JsonObject>>> resultHandlerCaptor;
#Test
public void test() {
AsyncResult<JsonObject> result = Future.succeededFuture(new JsonObject().put("status", "success"));
Mockito.verify(dbService).saveJobDetails(Mockito.any(JsonObject.class), resultHandlerCaptor.capture());
Handler<AsyncResult<JsonObject>> handler = resultHandlerCaptor.getValue();
handler.handle(result);
But when I am running this test getting an Exception
Wanted but not invoked:
dbService.saveJobDetails(
<any io.vertx.core.json.JsonObject>,
<Capturing argument>
);
Actually, there were zero interactions with this mock.

Junit Test case : java.lang.exception: json can not be null or empty

I am trying to write Test case for controller using JUnit and mockito. But I am getting error as JSON can not be null or empty. can any one please tell me what I m doing wrong?
DepartmentController
#RestController
#RequestMapping("/api.spacestudy.com/SpaceStudy")
public class DepartmentController {
#Autowired
DepartmentService depService;
#GetMapping("/Control/SearchFilter/loadDepartments")
public ResponseEntity<Set<Department>> findDepName() {
Set<Department> depname = depService.findDepName();
return ResponseEntity.ok(depname);
}
DepartmentControllerTest
#RunWith(SpringJUnit4ClassRunner.class)
public class DepartmentControllerTest {
private MockMvc mockMvc;
#Mock
public DepartmentService depService;
#InjectMocks
DepartmentController departmentController;
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(departmentController).build();
}
#Test(timeout = 10000)
public void findDepNameTest() throws Exception
{
Department dep = new Department();
dep.setsDeptName("ABC");
Set<Department> department = new HashSet<Department>();
department.add(dep);
Mockito.when(depService.findDepName()).thenReturn(department);
mockMvc.perform(get("/api.spacestudy.com/SpaceStudy/LoadDept").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].sDeptName" , is("abc")));
}
}
Failure Trace
java.lang.AssertionError: No value at JSON path "$[0].sDeptName", exception: json can not be null or empty
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:245)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:73)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:87)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.spacestudy.DepartmentControllerTest.findDepNameTest(DepartmentControllerTest.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
I found my mistake. I am giving wrong path for get Request in above code. I changed that path and its working properly.
mockMvc.perform(get("/api.spacestudy.com/SpaceStudy/Control/SearchFilter/loadDepartmentsLoadDept").accept(MediaType.APPLICATION_JSON))

Run Spring Boot Unit tests ignoring CommandLineRunner

I'm trying to write spring boot unit tests but have some problems with CommandLineRunner which runs entire app when I run unit tests.
App.class
#SpringBootApplication
#Profile("!test")
public class App implements CommandLineRunner {
#Autowired
private ReportService reportService;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
#Override
public void run(String... args) throws Exception {
if (args.length == 0)
reportService.generateReports();
if (args.length > 0 && args[0].equals("-p"))
for (Report report : reportService.showReports())
System.out.println(report.getId() + " : " + report.getTimestamp());
}
}
ReportServiceTest.class
#RunWith(SpringRunner.class)
#SpringBootTest(classes = App.class)
#ActiveProfiles("test")
public class ReportServiceTest {
#Autowired
private ReportRepository reportRepository;
#Autowired
private ReportService reportService;
#Test
public void testShowReports() {
List<Report> expectedReports = new ArrayList<>(3);
for(int i = 0; i< 3; i++) {
expectedReports.add(reportRepository.save(new Report()));
}
List<Report> actualReports = reportService.showReports();
assertEquals(expectedReports.size(), actualReports.size());
}
What I need to do that CommandLineRunner will be ignored when run in tests but all ApplicationContext, JPA and so on will be initialized?
UPDATE
It seems I have found the solution:
Added #Profile("!test") to App.class
Created new AppTest.class in test directory where I initialize only SpringApplication without CommandLineRunner
Added #ActiveProfile("test") to ReportServiceTest.class
AppTest.class
#SpringBootApplication
#Profile("test")
public class AppTest {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(AppTest.class);
app.setLogStartupInfo(false);
app.run(args);
}
}

Spring boot How to access Appconfig properties in test case

I am new to web services and spring boot. I have written a service for which I am now writing a test case.
My application gets Soap request, parses the body and saves contents into database.
My test case tests this service.
When I run the application and send a request from Postman, it runs alright. But when I call my service method from test case, I get nullpointer for JaxBcontext.
I have declared Jaxbcontext in my AppConfig.java (which is annotated with #Configuration and my jaxb is a bean with #Bean annotation) in my service, I have #autowire to use jaxbcontext.
I have pasted code snippets for clarity. Please advise me what I am doing wrongly here.
My test case
public class ReferralExchangeEndpointTest {
ReferralExchangeEndpoint referralExchangeEndpoint = new ReferralExchangeEndpoint();
JAXBContext jbcTest;
Marshaller marshaller;
Unmarshaller unmarshaller;
public ReferralExchangeEndpointTest() throws JAXBException {
}
#Before
public void setUp() throws Exception {
jbcTest = JAXBContext.newInstance(
"our app schema"); // this is working fine, I have replaced schema with this text for posting it in stack.
ObjectFactory factory = new ObjectFactory();
marshaller = jbcTest.createMarshaller();
unmarshaller = jbcTest.createUnmarshaller();
}
#Test
public void send() throws Exception {
File payload = new File("payload.xml");
Object x = unmarshaller.unmarshal(payload);
JAXBElement jbe = (JAXBElement) x;
System.out.println(jbe.getName());
Object test = jbe.getValue();
SendRequestMessage sendRequestMessage = (SendRequestMessage) jbe.getValue();
// Method in test.
referralExchangeEndpoint.send(sendRequestMessage);
}
}
My service class
#Endpoint
public class ReferralExchangeEndpoint {
public static final Logger logger = LoggerFactory.getLogger(ReferralExchangeEndpoint.class);
#Autowired
private JAXBContext jaxbContext;
#Autowired
.
.
.
private Form parseBody(String payLoadBody) {
try {
Unmarshaller um = jaxbContext.createUnmarshaller();
return (Form) um.unmarshal(new StringReader(payLoadBody));
} catch (Exception e) {
throw new RuntimeException("Failed to extract the form from the payload body", e);
}
}
My appconfig file
#Configuration
public class AppConfig {
#Bean
public JAXBContext jaxbContext() throws JAXBException {
return
JAXBContext.newInstance("packagename");
}
#Bean public MessagingService messagingService() {
return new MessagingService();
}
}
Thanks.
Kavitha.
** Solved **
My test case now looks like this.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {AppConfig.class})`
public class ReferralExchangeEndpointTest {
#Autowired
ReferralExchangeEndpoint referralExchangeEndpoint;
#Autowired
private JAXBContext jaxbContext;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
#Before
public void setUp() throws Exception {
marshaller = jaxbContext.createMarshaller();
unmarshaller = jaxbContext.createUnmarshaller();
}
#Test
public void send() throws Exception {
File payload = new File("src/test/resources/payload.xml");
JAXBElement jbe = (JAXBElement) unmarshaller.unmarshal(payload);
SendRequestMessage sendRequestMessage = (SendRequestMessage) jbe.getValue();
JAXBElement<SendResponseMessage> response = referralExchangeEndpoint.send(sendRequestMessage);
//TODO add remaining assertions on response after confirming what should the service return for these attributes.
assertEquals("SiteId wrong in response: ", "siteId", response.getValue().getSiteId());
}
}`

Arquillan EJB test not running

I wrote an Arquillan test, but nothing seems to happen after deployment annotation
#RunWith(Arquillian.class)
public class EjbTest {
#Inject
private RepAlertManager ejb;
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "foo.jar")
.addClasses(RepAlertManagerImpl.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
#Test
public void testEjb() throws IOException, SQLException {
try
{
List<Long> result = ejb.doSomething("ENTRATE");
for(Long temp:result){
System.out.println(temp);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I run it from Eclipse as JUnit Test, but debug goes out deployment method after nothing happens