簡體   English   中英

有沒有辦法在使用Spring或Spring Boot的JUnit測試中使用Autowired構造函數?

[英]Is there a way to use Autowired constructor in JUnit test using Spring or Spring Boot?

假設我有一個包含幾個Spring bean的測試配置,這些配置實際上是被模擬的,並且我想在JUnit測試套件中指定這些模擬的行為。

@Profile("TestProfile")
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {
        "some.cool.package.*"})
public class IntegrationTestConfiguration {

    @Bean
    @Primary
    public Cool cool() {
        return Mockito.mock(Cool.class);
    }
}

// ...

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ActiveProfiles("TestProfile")
public class CoolIntegrationTest {

    private final Cool cool;

    @Autowired
    public CoolIntegrationTest(Cool cool) {
        this.cool = cool;
    }

    @Test
    public void testCoolBehavior {
        when(cool.calculateSomeCoolStuff()).thenReturn(42);
        // etc
    }
}

如果運行此測試,我將得到:

java.lang.Exception: Test class should have exactly one public zero-argument constructor

我知道解決方法,例如在測試中使用自動裝配字段,但是我想知道是否有辦法在JUnit測試中使用自動裝配注釋?

除了args構造函數,您還需要另外一個no-args構造函數。 嘗試添加它,並檢查是否仍然發生此異常。

@Autowired
public CoolIntegrationTest(Cool cool) {
        this.cool = cool;
    }

public CoolIntegrationTest() {}

問題不是自動裝配,而是無參數構造函數。 JUnit測試類應具有一個無參數的構造函數。 要實現您想要做的事情,您應該執行以下操作:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ActiveProfiles("TestProfile")
@ContextConfiguration(classes = {IntegrationTestConfiguration.class})
public class CoolIntegrationTest {

    @Autowired
    private final Cool cool;

    @Test
    public void testCoolBehavior {
        when(cool.calculateSomeCoolStuff()).thenReturn(42);
        // etc
    }
}

contextConfiguration批注告訴spring用於測試的配置,並且自動裝配字段而不是構造函數將允許您測試spring bean。

要使用Spring運行測試,您必須添加@RunWith(SpringRunner.class)並確保將您的類添加到類路徑中。 有幾種方法可以做到這一點。 即,將類添加到MVC配置@WebMvcTest({Class1.class, Class2.class})或使用@ContextConfiguration

但是我看到了您的代碼,我想使用@Mock@MockBean模擬您的bean會更容易。 這樣會容易得多。

JUnit要求測試用例具有一個無參數的構造函數,因此,由於您沒有一個構造函數,因此異常發生在接線過程之前。

因此,在這種情況下,構造函數自動裝配不起作用。

那么該怎么辦?

有很多方法:

最簡單的一種方法(因為有春天)是利用@MockBean注釋:

@RunWith(SpringRunner.class)
@SpringBootTest
 ....
class MyTest {

   @MockBean
   private Cool cool;

   @Test
   void testMe() {
      assert(cool!= null); // its a mock actually
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM