春ブーツユニットテストは、全体のプログラムを実行します

チャバFarago:

私は春ブーツとの統合テストを実施したいと思います。私はで始まるspring-boot-starter-test依存関係、バージョン2.2.5.RELEASE

私は、次のコンポーネントがあります。

@Component
public class MyMath {

    public int add(int a, int b) {
        return a + b;
    }

}

メインプログラムは次のようになります。

@SpringBootApplication
public class Main implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Autowired
    private MyMath myMath;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(myMath.add(2, 3));
    }

}

これまでのところ、とても良い - それは期待通りに動作します。私はユニットテストを追加したいと思います:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyMathTest {

    @Autowired
    private MyMath myMath;

    @Test
    public void testSaveAndList() {
        assertEquals(5, myMath.add(2, 3));
    }

}

また、これは動作しますが、ログによると、それは全体のプログラムを実行します私は、プログラム自体、ちょうど実行しないMyMath.add()機能を。どうやってやるの?

私は、これまでに以下のことを試してみました:

  • @RunWith(SpringJUnit4ClassRunner.class) 同じ結果を提供します。
  • 省略@SpringBootTestの結果NoSuchBeanDefinitionException
  • それが動作する以下のような豆の代わりに、コンポーネントを持つようにコードを再フォーマットします。

MyMath 注釈なし:

public class MyMath {

    public int add(int a, int b) {
        return a + b;
    }

}

Main 同じまま。

@Configuration
public class AppConfig {

    @Bean
    public MyMath getMyMath() {
        return new MyMath();
    }
}

そしてテスト:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class MyMathTest {

    @Autowired
    private MyMath myMath;

    @Test
    public void testSaveAndList() {
        assertEquals(5, myMath.add(2, 3));
    }

}

それでは、私が行うことができないと、全体のプログラムを実行せずにコンポーネントをテストすることです。すべての私を助けてもらえますか?ありがとう!

pvpkiran:

あなたは、あなたのコードをリファクタリングする必要はありません。そのままちょうどMyMathクラスを保ちます

@Component
public class MyMath {

    public int add(int a, int b) {
        return a + b;
    }
}

あなたのテストクラスは次のように変更します

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyMath.class)
public class MyMathTest {

    @Autowired
    private MyMath myMath;

    @Test
    public void testSaveAndList() {
        assertEquals(5, myMath.add(2, 3));
    }

}

あなたのMyMathクラスがautowired他の依存関係を持っている場合、これは少し複雑になります。そして、あなたはモックを使用する必要があります。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=373210&siteId=1