在我的一個JUnit測試類中注入依賴項有些麻煩。 我相信TestApplication不是包掃描或未被加載。下面在Junit測試中無法注入依賴項
代碼:
package com.mitto.repositories;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.mitto.MittoApplicationTests;
import com.mitto.domain.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= { MittoApplicationTests.class })
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@DatabaseSetup("UserRepositoryTest.xml")
public class UserRepositoryTest {
@Autowired
UserRepository repository;
private static final long FACEBOOK_ID = 1234567;
@Test
public void getUserById() {
User user = repository.findOne(1L);
assertNotNull(user);
assertEquals(user.getFacebookId(), FACEBOOK_ID );
}
}
MittoApplicationTests.java
package com.mitto;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MittoApplicationTests {
@Test
public void contextLoads() {
}
}
UserRepository.java
package com.mitto.repositories;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.mitto.domain.User;
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long>{
User findByFacebookId(long facebookId);
User findByAuthToken(String token);
}
我看不出什麼錯。
感謝嶽敏君,幫我解決我的問題,並提供了一個更好地瞭解我。乾杯! – scottazord
@scottazord具有類的值的'@ SpringBootTest'指定用於加載ApplicationContext的類。除此之外,它並沒有做太多的事情。 –
很高興幫助。 –