Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在@PostConstruct中为Groovy Spock测试用例模拟语句_Java_Spring Boot_Unit Testing_Groovy_Spock - Fatal编程技术网

Java 如何在@PostConstruct中为Groovy Spock测试用例模拟语句

Java 如何在@PostConstruct中为Groovy Spock测试用例模拟语句,java,spring-boot,unit-testing,groovy,spock,Java,Spring Boot,Unit Testing,Groovy,Spock,我正在为其编写groovy测试用例的服务类中有@PostConstruct。我在init()方法中模拟了调用,但它不起作用: @Service @Transactional public class ServiceImpl implements Service{ private Dao testDao; @Autowired private AbcDao abcDao; @PostConstruct public void init() {

我正在为其编写groovy测试用例的服务类中有@PostConstruct。我在init()方法中模拟了调用,但它不起作用:

@Service
@Transactional
public class ServiceImpl implements Service{

private Dao testDao;
@Autowired
private AbcDao abcDao;
    
        @PostConstruct
        public void init() {        
          testDao = abcDao.findByName("testString");
          Assert.notNull(testDao, "testDao not found");
          
        } 

        public method toBeTest(){
        
        }
}
我将groovy测试用例编写为:

public class ServiceSpec{
        
    @Autowired
    Service service
    
      def 'Test method'() {
        given:
        Dao test=new Dao()
        abcDao.findByName("testString") >>  test
      
        when:
        service.toBeTest()
        then:
        true

    }
    
    }


But it doesn't work and fail in the Assert statement.

这不是回答你的问题,但很重要。你的代码离理想还很远
ServiceImpl
应该有一个构造函数来接收它所需要的依赖项,而不是在私有字段上用
@Autowired
自动注入依赖项。使用这种方法可以在不考虑Spring的情况下对类进行单元测试。第二个
@PostConstruct
主要用于与较旧(设计不良)的代码兼容,不应用于初始化对象-这是构造函数的责任。同意。但由于某些原因,ServiceImpl的代码现在无法更改。如果根本无法解决此问题,请给出建议。一般性意见,不回答您的问题:代码总是可以更改的。其他一切都是借口,特别是当给出的理由只是“由于某些原因”时。编写自动化测试的一个主要原因是验证和改进应用程序设计,这比测试现有代码更重要。测试自动化,尤其是TDD是设计工具,而不仅仅是QA工具。QA只是一个积极的副作用。可测试性本身很重要,因为如果做得好,它将与模块化和组件/依赖性解耦齐头并进。