Help coderanch get a
new server
by contributing to the fundraiser

Ish Fad

Greenhorn
+ Follow
since Aug 09, 2011
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
In last 30 days
0
Forums and Threads

Recent posts by Ish Fad

Hi
I am new to Mockito and trying to write a test for my demo project. I have a project, using Spring 5 and Hibernate. I have a DAO class which use Hibernate session and query.

@Repository
@Transactional
public class CustomerDaoImpl implements CustomerDao {

@Autowired
   private SessionFactory sessionFactory;

@Override
public Customer getCustomerById(int id) {
Session session = null;
Customer customer = null;

try{
session = sessionFactory.openSession();
customer = session.find(Customer.class, id);
}catch(Exception e) {
throw (e);
}finally {
session.close();
}
return customer;
}
}

// Test Class
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(locations = "classpath:spring-hibernate-config-test.xml")
public class CustomerDaoTest {

@InjectMocks
private CustomerDaoImpl customerDao;

@Mock
SessionFactory sessionFactory;

Customer customer;

@Before
public void setupMock(){
    MockitoAnnotations.initMocks(this);
    sessionFactory = mock(SessionFactory.class);
    customerDao.setSessionFactory(sessionFactory);
}

@Test
@Transactional
@Rollback(true)
@DisplayName("DAO: Find customer by given id")
public void testGetCustomerById() {
int customerId = 14;
Customer customer = new Customer(14, "Mike");
when(sessionFactory.openSession().find(Customer.class, customerId)).thenReturn(customer);

assertNotNull(customer);
    assertEquals(customerId, customer.getIfCustomerId());
}
}

Error:
java.lang.NullPointerException
at com.primis.dao.CustomerDaoTest.testGetCustomerById(CustomerDaoTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)

For some reason my session is null. Please can someone advice where I am going wrong.

Thank you
2 years ago
Hi

I am new Spring boots, JUnit 5 and Mockito.
I am trying to learn this technolgy.
I have simple RestController with one method createUser.
When I test this controller method through Postman, it work fine.
But when run unit test (Shown below), I am getting NullPointerException (marked inside method).
It is not creating userResponse. Here is the code;

Please can someone advice me where I am going wrong.

@RestController
@RequestMapping("/user")
public class UserRestController {

@Autowired
UserService userService;

@PostMapping(path="save", consumes= {MediaType.APPLICATION_JSON_VALUE}, produces= {MediaType.APPLICATION_JSON_VALUE})
public String createUser(@RequestBody User user) {
User userResponse = userService.createUser(user);
System.out.println("userResponse ..: " + userResponse );  // These is null when Test run

return String.valueOf(userResponse.getId());
}
} //  end UserController


@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Override
public User createUser(User user) {
User userResponse = userRepository.save(user);
return userResponse;
}
}

@WebMvcTest(UserRestController.class)
public class UserRestControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
UserService userService;

@Test    
@DisplayName("UserRestController createUser Test")
public void createUserTest() throws JsonProcessingException, Exception {

User newUser = new User("Mr", "Dabby", "Wall", 27);
User savedUser = new User(1, "Mr", "Dabby", "Wall", 27);

when(userService.createUser(newUser)).thenReturn(savedUser);

String url = "/user/save";
this.mockMvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newUser)))
.andExpect(status().isOk())
.andExpect(content().string("1")
);
}
}


Here is error I am getting;
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
Caused by: java.lang.NullPointerException
at com.ics.restController.UserRestController.createUser(UserRestController.java:37)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)


3 years ago
Hi
I have boolean field in action
testMeAction.class
private boolean testMe with stter and getter.

testMeAction-validation.xml

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>

<validator type="expression" short-circuit="true">
<param name="expression"><![CDATA[(testMe == false) && myGroup == null]]></param>
<message key="user.message" />
</validator>

</validators>

I would like to validate and display message when testMe and myGroup
But for some reason, it allways diplaying message, what ever value of testMe is.

Please can someone advice, where I am going wrong.

Thanks
9 years ago
Hi

I am new to spring environment. I have created small test spring project through STS.
Project name: SPTest
base package name: uk.co.ifTest

When I run and open this project browser through Eclipse. It work fine, but url, it put in the browser is http://localhost:8080/ifTest/, instead of http://localhost:8080/SPTest/.
I guess, it is adding base package name.

Is there any way I can open project with http://localhost:8080/SPTest/.

Thanks
ish
9 years ago
Hi

I have installed tomcat 7 on laptop. I have tested tomcat and it is running fine.
I have created simple war file with just one html page.
I have added this war file to webapps folder of the tomcat.
When I try to open this page from the browser, I am getting following error

message /if2.html

description The requested resource (/if2.html) is not available.

Please could you help me.

Many thanks
12 years ago
Hi
I am trying to connect to SQLServer 2008 Express.
I have downloaded jtds-1.2.5.jar.
I have enable TCP/IP and user and password do exist with full right.

I am getting following error

<code>
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:410)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at conn.DBConnecion.dbConnect(DBConnecion.java:10)
at conn.TestConnection.main(TestConnection.java:9)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:307)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:257)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:311)
</code>

can some one help

many thanks
Hi

I am using MYSQL Database with Eclipse helios.
I am having problem adding object to POJO (Class created by Hibernate reverse engineering).
I have two tables customer and stitle. I have created One-to-Many relationship in MYSQL between this two tables.
titleId is foreign key in customer table. so one to many relation exist.

customer

customerId as int(11) primary Key
titleId as Int(11) foreignKey FK_CTitleId (which is match to titleId in stitle table)
firstname as string(45)

stable

titleId as int(11) primary Key
title as string(45)

When I run reverse engineering, I get two object STitle.java and Customer.java.
Also get two Customer.hbm.xml and Stitle.hbm.xml.
But I am getting titleId in Customer object as an Integer and not as STitle object.

Here is my hibernate-reverse-engineering file.


JAVA object it created



I don't understand why it is creating titleId as integer. It suppose to be object for table sTitle.

Please can someone help me.

Many thanks
I am using MYSQL Database.
I having problem adding object to POJO (Class created by Hibernate reverse engineering).
I have two tables customer and title. I have created One-to-Many relationship in MYSQL between this two tables.
titleId is foreign key in customer table. so one to many relation exist.
Here is my hibernate-reverse-engineering file.



JAVA object it created



I don't understand why it is creating titleId as integer. It suppose to be object for table sTitle.

Please can someone help me.

Many thanks

[Fixed code tags - Matthew]