相关疑难解决方法(0)

JUnit 5不执行使用BeforeEach注释的方法

JUnit 5不会在使用注释注释的测试类中调用我的方法@BeforeEach,其中我初始化测试中所需的测试对象的一些字段.当试图在测试方法(注释方法@Test)中访问这些字段时,我显然得到一个NullpointerException.所以我在方法中添加了一些输出消息.

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class TestClass {
   private String s;

   public TestClass() {

   }

   @BeforeEach
   public void init() {
      System.out.println("before");
      s = "not null";
   }

   @Test
   public void test0() {
      System.out.println("testing");
      assertEquals("not null", s.toString());
   }

}
Run Code Online (Sandbox Code Playgroud)

在运行测试的输出中,mvn clean test我从test0()注释@Test注释的方法中获取"测试"消息,但不打印"之前"消息.

Running de.dk.spielwiese.TestClass
!!!testing!!!
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0 sec <<< FAILURE!
de.dk.spielwiese.TestClass.test0()  Time elapsed: 0 sec  <<< FAILURE! …
Run Code Online (Sandbox Code Playgroud)

java maven junit5

17
推荐指数
5
解决办法
6983
查看次数

我可以编写一个使用自动装配的 Spring bean 的 Kotlin 扩展函数吗?

我正在尝试创建一个扩展函数,其实现使用 Spring bean。通过在包的顶层定义扩展函数似乎不可能做到这一点。我试过这个:

@Component
class Converter {

    companion object {
        @Autowired
        lateinit var transformer: Transformer

        fun Class1.convert(): Class2 {
            return Class2 (this, transformer.transform(someStringProperty))
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

wheretransform是一个将某个字符串转换为另一个字符串的函数,并且Class1是某个具有someStringProperty属性的类。我希望其他类可以import pkg.Converter.Companion.convert然后能够使用x.convert()wherex是类型的对象Class1

语法有效,x.convert()在其他类中使用编译正常。但它在运行时导致异常:kotlin.UninitializedPropertyAccessException: lateinit property transformer has not been initialized

看起来 Spring 没有自动装配变量,因为它位于伴随对象中,而不是实际的组件对象中。

注释伴随对象@Component不起作用。

我不认为Class1.convert直接在内部移动Converter会起作用,因为然后使用x.convert()将需要Converter对象的实例,并且我不知道如何使用扩展函数语法来做到这一点。

有什么办法可以做到这一点,还是必须放弃扩展函数语法?

spring kotlin

5
推荐指数
2
解决办法
4759
查看次数

标签 统计

java ×1

junit5 ×1

kotlin ×1

maven ×1

spring ×1