单元测试与Spring框架

版权声明:欢迎转载,转载时请注明出处 https://blog.csdn.net/xfzero/article/details/79154364

单元测试与Spring框架

参考博客
源代码

当进行单元测试的时候,需要给对象的依赖一个mock对象
但是对于Spring项目对象的私有成员,我们无法访问给他一个mock对象.这个时候我们就需要ReflectionTestUtils,他能够像Spring一样注入filed,通过手动给私有成员一个mock对象

public class ObjectA {
    private String pwString;

    public String getPwString() {
        return pwString;
    }

    public void setPwString(String pwString) {
        this.pwString = pwString;
    }
}

被测试类

public class ObjectB {
    private ObjectA objectA;

    public ObjectA getObjectA() {
        return objectA;
    }

    public void setObjectA(ObjectA objectA) {
        this.objectA = objectA;
    }

}

测试类

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class testMockito {
    @Test
    public void test() {
        ObjectB objectB = new ObjectB();
        ObjectA objectA = mock(ObjectA.class);
        when(objectA.getPwString()).thenReturn("hello A");
        //"objectA"是通过成员变量名字确定的
        ReflectionTestUtils.setField(objectB, "objectA", objectA);

        ObjectA actucalA = objectB.getObjectA();
        assertEquals("hello A", actucalA.getPwString());
    }
}

webx框架(模仿Spring框架单元测试程序错误

10-15

[img]http://dl.iteye.com/upload/attachment/570731/1631fcc7-df46-30bf-b5a6-6b633022f927.jpg[/img]rnrn麻烦哪位帮我看个问题,sql-map-oracle-home.xml文件中红框部分的配置去掉,DemoDAOTest就能正确运行,加上之后DemoDAO的测试程序无法运行,就会出现如下的错误,是怎么回事rnorg.springframework.beans.factory.BeanCreationException: rnError creating bean with name 'demoDao': Injection of resource rnfields failed; nested exception is org.springframework.beans.factory.BeanCreationException: rnError creating bean with name 'oracleBaseDao' defined in file rn[D:\work\datasky\common\config\target\classes\META-INF\beans\config\oracle-data-source-config.xml]:rn Cannot resolve reference to bean 'oracleSqlMapClient' while setting bean property 'sqlMapClient';rn nested exception is org.springframework.beans.factory.BeanCreationException: rn Error creating bean with name 'oracleSqlMapClient' defined in file rn [D:\work\datasky\common\config\target\classes\META-INF\beans\config\oracle-data-source-config.xml]:rn Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: rn Failed to parse config resource: file [D:\work\datasky\common\config\rn target\classes\META-INF\ibatis\config\sql-map-oracle-home.xml]; rn nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. rn Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. rn Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. rn Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMap/select'. rn Cause: com.ibatis.sqlmap.client.SqlMapException: There is no result map named java.util.List in this SqlMap.

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试