java 使用动态数据源模拟方法

uoifb46i  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(138)

我需要测试这个方法,但是我不知道在不连接到服务器上的数据库的情况下如何进行测试。

public List<String> searchQuery(String key) {
    List<String> resultList = null;
    try {
        this.createConnection(CheckDataServlet.getKey(Integer.parseInt(key)).getConnection().getName());
        stmt = conn.prepareStatement(CheckDataServlet.getKey(Integer.parseInt(key)).getSelect().trim());
        rs = stmt.executeQuery();
        resultList = this.getValues(rs);
    } catch ( SQLException e) {
        Archicon.getLogger().error("ValidationData.searchQuery error: "+e);
    }finally {
        this.closeConnection("searchQuery",conn,stmt,rs);
    }
    if (resultList == null) {
        resultList = new ArrayList<>();
    }

    return resultList;
}

public void createConnection(String key){
        try {
            ds = (DataSource) Archicon.getResource("jdbc/"+key);
            conn = ds.getConnection();
        } catch (SQLException | NamingException e) {
            throw new RuntimeException(e);
        }
    }

我试着用Mockito测试,但总是给予我这个错误,因为数据源为空:

java.lang.NullPointerException
at it.sisal.archicon.model.valor.ValidationData.createConnection(ValidationData.java:157)
at it.sisal.archicon.model.valor.ValidationData.searchQuery(ValidationData.java:23)
at it.sisal.archicon.model.valor.AwpSapNewRepositoryTest.searchQuery(AwpSapNewRepositoryTest.java:95)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

我试着构建这个测试类:

@RunWith(MockitoJUnitRunner.class)
public class AwpSapNewRepositoryTest {
     @Mock
   private ValidationData validationData;
@Before
    public void setup() throws SQLException {
        MockitoAnnotations.initMocks(this);
     try (final MockedStatic<Archicon> archicon= Mockito.mockStatic(Archicon.class)) {
      DataSource ds = mock(DataSource.class);
      archicon.when(() -> Archicon.getResource(any())).thenReturn(ds);
     }
 @Test
    public void searchQuery() throws NamingException {

      //  System.setProperty("jboss.server.config.dir","C:\\Program Files\\wildfly-18.0.0.Final\\standalone\\configuration\\archicon");
       Archicon.setConfigPath("C:\\Program Files\\wildfly-18.0.0.Final\\standalone\\configuration\\archicon");
        when(validationData.searchQuery("11")).thenReturn(new ArrayList<>(List.of("Name, 99","Stuff, 99")));
        validationData = new ValidationData();
        assertEquals(true,validationData.searchQuery("11").size()>0);
    }

有人知道测试这个方法的好方法吗?

nbnkbykc

nbnkbykc1#

可以使用mockito模拟Archicon类的静态方法,以返回DataSource的模拟:

try (final MockedSatic<Archicon> archicon= Mockito.mockStatic(Archicon.class)) {
    DataSource ds = mock(DataSource.class);
    archicon.when(() -> Archicon.getResource(any())).thenReturn(ds);
}

相关问题