あなたがしたい場合は、まだ春のコンテキスト内でテストを実行し、Spring構成クラス内の必要なプロパティを設定することができます。あなたはJUnitのを使用している場合は、SpringJUnit4ClassRunnerを使用し、そのようなあなたのテストのための専用コンフィギュレーション・クラスを定義します。
テスト中の
クラス:
@Component
public SomeClass {
@Autowired
private SomeDependency someDependency;
@Value("${someProperty}")
private String someProperty;
}
テストクラス:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SomeClassTestsConfig.class)
public class SomeClassTests {
@Autowired
private SomeClass someClass;
@Autowired
private SomeDependency someDependency;
@Before
public void setup() {
Mockito.reset(someDependency);
@Test
public void someTest() { ... }
}
およびコンフィギュレーションクラスのこのテスト:
@Configuration
public class SomeClassTestsConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() throws Exception {
final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Properties properties = new Properties();
properties.setProperty("someProperty", "testValue");
pspc.setProperties(properties);
return pspc;
}
@Bean
public SomeClass getSomeClass() {
return new SomeClass();
}
@Bean
public SomeDependency getSomeDependency() {
// Mockito used here for mocking dependency
return Mockito.mock(SomeDependency.class);
}
}
これは、私はお勧めしませんこのアプローチでは、参考のためにここに追加しました。私の意見では、はるかに良い方法は、Mockitoランナーを使用することです。その場合は、Spring内でテストを実行しないでください。これははるかに明確で簡単です。
まさに私が何をしようとしていたと私は私のクラス内の値を設定するために探していた、ありがとう! – Kyle
フィールドをデフォルトアクセス(パッケージ保護)に変更して、テストに簡単にアクセスできるようにすることで、Springの依存関係をまったく使用しないことさえできます。 –
例: 'org.springframework.test.util.ReflectionTestUtils.setField(classUnderTest、" field "、" value ");' – Olivier