JUNIT Test case not passed - java

I have class where I am written code to create a new category and if category not found it will throw "CategoryNotFoundException". I have written the test cases but it was not passed.
If I omit "expected= CategoryNotFoundException.class" from my JUNIT test case it will pass. But I don't want to change any portion in my Test cases. I tried by throwing the exception from my implemented class but still it is not passed.I am stucking there to pass the TestCase.
DAO code::
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
Session session=this.sessionFactory.getCurrentSession();
session.save(category);
return true;
//return isInserted;
}
Tried with the below code as well but TC not passed:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try{
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
}
catch(Exception ex){
return false;
}
}
JUNIT Code::
#Test(expected= CategoryNotFoundException.class)
#Rollback(true)
public void testCreateCategoryFailure() throws CategoryNotFoundException {
categoryDAO.createCategory(category);
Category savedCategory = categoryDAO.getCategoryById(2);
assertNotEquals(category, savedCategory);`enter code here`
}

You are trying to throw an exception but you are catching also, so you should rethrow If it is necessary, so you should try to do this:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try {
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
} catch(CategoryNotFoundException exc) {
throw exc;
} catch(Exception ex){
return false;
}
}

Related

Prettifying exception handling in function

Can this func. not be prettified?
Can the the catch clause be left empty, I have heard it's frowned up on.
apiClient.accountList() is where the exception can occur.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
try {
for (Account account : apiClient.accountList()) {
if (account.getUuid().equals(accountUuid)) {
return Optional.of(account);
}
}
} catch (ApiException e) {
return Optional.empty();
}
return Optional.empty();
}
If you're very motivated to avoid the duplicate return statement, a simple tweak to the control-flow should do it. As mentioned in the comments, logging exceptions is often a good idea.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
Optional<Account> result = Optional.empty();
try {
for (Account account : apiClient.accountList()) {
if (account.getUuid().equals(accountUuid)) {
result = Optional.of(account);
break;
}
}
}
catch (ApiException e) { /* Log exception */ }
return result;
}
You can use Stream, assuming getUuid does not throw an ApiException.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
try {
return apiClient.accountList().stream()
.filter(account -> account.getUuid().equals(accountUuid))
.findAny();
} catch (ApiException e) {
/* Log exception */
return Optional.empty();
}
}
Actually instead of collection returning methods like accountList() it more and more makes sense to use Streams, accountStream().

Junit test case for 'if' condition in code

I am getting null pointer exception at if condition in the below method.Here is my method and junit test class i am working.
METHOD
#Override
public Event getDisplayEventDetails(String ceccid,
String ceocid) {
Event evnt = null;
if(!(validate.isStringBlank(ceccid)))
{
if(!(validate.isStringBlank(ceocid)))
{
String dispEventUri = eventServicesUrl;
eventSrvcLogger.debug("dispEventUri..."+dispEventUri);
try {
ResponseEntity<Event> responseEntity = restTemplate.getForEntity(dispEventUri , Event.class);
evnt=responseEntity.getBody();
if(responseEntity.getStatusCode().toString().equals("200")){
if(evnt.getValue().length > 0){
for(int i=0;i<evnt.getValue().length;i++){
DisplayValue val = new DisplayValue();
val = evnt.getValue()[i];
eventSrvcLogger.debug(val.toString());
}
} else{
evnt.setStatusCode(responseEntity.getStatusCode().toString());
evnt.setStatus(Boolean.FALSE);
evnt.setMessage("Exception occured in handling the request BAD REQUEST");
}
}
} catch (RestClientException e) {
eventSrvcLogger.error("DisplayEventServiceImpl displayEventDetail() RestClientException",
e);
}
}
}
return evnt;
}
Junit class
#Test
public void testGetDisplayEventDetails() throws Exception{
//test setup with mocking, expectations, data population
String eventServicesUrl = "http://restUrl";
Event evnt = newEvent();
ResponseEntity<Event> responseEntity = new ResponseEntity<Event>(evnt, HttpStatus.OK);
DisplayValue[] dv = new DisplayValue[1];
DisplayValue dvalue = new DisplayValue();
dvalue.setFirst_name("Ron");
dv[0] =dvalue;
evnt.setValue(dv);
new NonStrictExpectations() {
{
restTemplate.getForEntity(anyString,evnt.class );returns(responseEntity);
}
};
EventService evntSrvcImpl = new EventServiceImpl();
ReflectionTestUtils.setField(evntSrvcImpl,"eventServicesUrl", eventServicesUrl);
ReflectionTestUtils.setField(evntSrvcImpl,"restTemplate", restTemplate);
}
//execute your test case
Event evnt1 = evntSrvcImpl.getDisplayEventDetails("ceccid", "ceocid");
//perform verifications and assertions
assertNotNull(evnt);
assertEquals(evnt.getValue()[0].getName(), evnt1.getValue()[0].getName());
}
On debugging its throwing null pointer exception
at this line of code
if(responseEntity.getStatusCode().toString().equals("200"))
How to set that value in the junit test class ?
I got it by adding below lines to junit test class:
HttpStatus statusCode= HttpStatus.OK;,
responseEntity.getStatusCode(); returns(statusCode);

Verify element is not displayed

I want to check that an element is not displayed. I have written the following code :
public boolean verifyelementNotDisplayed() {
try
{
if(element("element").isDisplayed())
return false;
else
{
logMessage("element not displayed");
return true;
}
}
catch(Exception e)
{
return false;
}
}
But my test fails.
Try this snippet:
public boolean verifyelementNotDisplayed() {
try{
return(!element("element").isDisplayed());
catch(Exception e){
return false;
}
}
And have a look at the is displayed method:
How does Selenium WebDriver's isDisplayed() method work
or:
Where is the implementation for the WebElement.isDisplayed() method in Selenium?
The following code worked
public boolean verifyNoelement() {
try
{
if(element("element").isDisplayed())
{
return false;
}
return false;
}
catch(Exception e)
{
logMessage("No element displayed");
return true;
}
}

Validating absence of an element

I have a test case:
Assert.assertTrue(test .verifyNoDrillDisplayForCourses());
and a boolean method verifyNoDrillDisplayForCourses which verifies element("xyz") is not displayed,
try{
if(element("xyz"). isDisplayed())
return false;
else return true;
}
catch (Exception e)
{
return false;
}
}
But the assertion fails as java .lang .AssertionError:expected [true] but found [false]. I am unable to figure out why?
The isDisplayed() method will throw an StaleElementReferenceException, if the given element is not in the DOM anymore. So you have to change the catch statement to return true;.
If you're testing for the presence of an element, if it's not found an exception will be thrown. So if you find it you're returning false, if you can't find it you're also returning false.
When testing for non-presence of an element you should have the catch block return true!
try{
if(element("xyz").isDisplayed()) {
return false;
} else return true;
}
catch (Exception e)
{
return false;
}
}
I believe your if statement is missing correct formatting from what you copied over.
I've amended it above, but in case try it like this:
if(element("xyz").isDisplayed()) {
return false;
} else return true;
Following code helped:
public boolean verifyNoelement()
{
try
{
if(element("element").isDisplayed())
{
return false;
}
return false;
}
catch(Exception e)
{
logMessage("No element displayed");
return true;
}
}

Expected exception not caught or not thrown?

I am testing a function that permit to connect to FTP server.
Here is one of my test who works properly:
#Test
public void connectTestValid()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("127.0.0.1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
if (!connectionSuccess)
{
fail("Expected Connection success");
}
}
I want to test if the connectFTP() method throw an exception when the serverAddress is invalid.
Here is my test:
#Test(expected = Exception.class)
public void connectTestInvalidServerAddress()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
}
Here is my function:
protected boolean connectFTP(FTPClient ftp)
{
try
{
ftp.connect(getAssetSource().getServerAddress());
if (!ftp.login(getAssetSource().getUsername(), getAssetSource().getPassword()))
{
logger.error("Login Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
{
logger.error("Connection Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
}
catch (Exception e)
{
e.printStackTrace();
return connectionSuccess = false;
}
return connectionSuccess = true;
}
Presently, the test doesn't work.
Thanks for your help!
The reason the test is not passing is that it is expecting an Exception to be thrown, but the exception is being caught inside the 'connectFTP' method, which is then returning false.
Whether you return false when connection fails or throw an exception depends on the semantics of your code. Based on the boolean return value, it seems like you're expecting false to be returned when there is an exception. In that case you'll want to do
org.junit.Assert.assertFalse(connectionSuccess);
instead of using (expected = Exception.class) in the #Test annotation.
it looks like you're catching an exception by yourself in your code
If you call the method 'connectFTP' from outside (it doesn't matter whether its a junit or not, it just won't throw an exception.
That's why your JUnit doesn't work.
BTW, it would be better not to work directly with Exception, but with its subtype relevant for your case.

Categories