Я пытаюсь проверить свое соединение с базой данных, когда я пытаюсь использовать запрос в IntelliJ IDEA IDE, он работает, но модульное тестирование не удалось. Я только начинаю с Java, так что я, вероятно, делаю что-то не так, можете ли вы сказать мне, как это сделать правильно? Я пытаюсь проверить, получаю ли я все значения из таблицы Workers, а второй тест - получить одно специальное значение из таблицы Workers.
Класс модели работника:
package com.bmp.bmp.model;
import javax.persistence.*;
@Entity
@Table(name = "WORKERS")
public class Workers {
@Id
@Column(name = "WORKER_ID")
private int workerId;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "LASTNAME")
private String lastname;
@Column(name = "WORKPLACE_ID")
private int workplaceId;
public Workers(int workerId, String firstname, String lastname, int workplaceId)
{
super();
this.workplaceId = workplaceId;
this.lastname = lastname;
this.firstname = firstname;
this.workerId = workerId;
}
public Workers()
{
super();
}
public int getWorkerId() {
return workerId;
}
public void setWorkerId(int workerId) {
this.workerId = workerId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getWorkplaceId() {
return workplaceId;
}
public void setWorkplaceId(int workplaceId) { this.workplaceId = workplaceId;
}
}
Рабочий класс репозитория:
package com.bmp.bmp.service.implement;
import com.bmp.bmp.model.Workers;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
@Repository
public class Worker implements com.bmp.bmp.service.interfaces.Worker
{
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void save(Workers workers) {
String query = "insert into Workers (WORKER_ID, FIRSTNAME, LASTNAME, WORKPLACE_ID) values ((select max(WORKER_ID)+1 from workers),?,?,?); commit;";
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, workers.getFirstname());
ps.setString(2, workers.getLastname());
ps.setInt(3, workers.getWorkplaceId());
int out = ps.executeUpdate();
if(out !=0){
System.out.println("Worker saved with id="+workers.getWorkerId());
}else System.out.println("Worker save failed with id="+workers.getWorkerId());
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public Workers getById(int id) {
String query = "select FIRSTNAME, LASTNAME, WORKPLACE_ID from WORKERS where WORKER_ID = ?";
Workers workers = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setInt(1, id);
rs = ps.executeQuery();
if(rs.next()){
workers = new Workers();
workers.setWorkerId(id);
workers.setFirstname(rs.getString("firstName"));
workers.setLastname(rs.getString("lastname"));
workers.setWorkplaceId(rs.getInt("workplace_id"));
System.out.println("Worker Found::"+workers);
}else{
System.out.println("No worker found with id="+id);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return workers;
}
@Override
public void update(Workers workers) {
String query = "update Workers set FIRSTNAME=?, LASTNAME=?, WORKPLACE_ID=? where WORKER_ID=?; commit;";
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
String firstName = ("'" + workers.getFirstname() + "'");
String lastName = ("'" + workers.getLastname() + "'");
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setInt(3, workers.getWorkplaceId());
ps.setInt(4,workers.getWorkerId());
int out = ps.executeUpdate();
if(out !=0){
System.out.println("Worker updated with id="+workers.getWorkerId());
}else System.out.println("No worker found with id="+workers.getWorkerId());
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public void deleteById(int id) {
String query = "delete from WORKERS where WORKER_ID=?; commit;";
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setInt(1, id);
int out = ps.executeUpdate();
if(out !=0){
System.out.println("Worker deleted with id="+id);
}else System.out.println("No worker found with id="+id);
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public List<Workers> getAll() {
String query = "select WORKER_ID, FIRSTNAME, LASTNAME, WORKPLACE_ID from WORKERS";
List<Workers> empList = new ArrayList<Workers>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
Workers workers = new Workers();
workers.setWorkerId(rs.getInt("worker_id"));
workers.setFirstname(rs.getString("firstname"));
workers.setLastname(rs.getString("lastname"));
workers.setWorkplaceId(rs.getInt("workplace_id"));
empList.add(workers);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return empList;
}
}
Рабочий юнитТест:
package com.bmp.bmp.service.implement;
import com.bmp.bmp.model.Workers;
import com.bmp.bmp.service.interfaces.WorkerInt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
public class WorkerTest {
@Autowired
Worker worker = new Worker();
@Test
public void getAll() {
List<Workers> workersList = worker.getAll();
workersList.forEach(System.err::println);
}
@Test
public void getById() {
Workers workers = worker.getById(7);
}
}
Сообщение об ошибке из консоли
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bmp.bmp.service.implement.WorkerTest': Unsatisfied dependency expressed through field 'worker'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bmp.bmp.service.implement.Worker' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bmp.bmp.service.implement.Worker' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 27 more