我试图运行一个简单的Junit测试,看看我的CrudRepositories是否确实在工作。

我一直得到的错误是:

无法找到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration或@SpringBootTest(classes=…) java.lang.IllegalStateException

Spring Boot不自己配置吗?

我的测试类:

@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JpaTest {

@Autowired
private AccountRepository repository;

@After
public void clearDb(){
    repository.deleteAll();
}

 @Test
 public void createAccount(){
     long id = 12;
     Account u = new Account(id,"Tim Viz");
     repository.save(u);
      
     assertEquals(repository.findOne(id),u);
      
 }
  
  
 @Test
 public void findAccountByUsername(){
     long id = 12;
     String username = "Tim Viz";
     Account u = new Account(id,username);
     repository.save(u);
      
     assertEquals(repository.findByUsername(username),u);
      
 }
  

Spring Boot应用程序启动器:

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"domain.repositories"})
@ComponentScan(basePackages = {"controllers","domain"})
@EnableWebMvc
@PropertySources(value    {@PropertySource("classpath:application.properties")})
    @EntityScan(basePackages={"domain"})
    public class Application extends SpringBootServletInitializer {
        public static void main(String[] args) {
            ApplicationContext ctx = SpringApplication.run(Application.class, args);         
 
        }
    }

我的库:

public interface AccountRepository extends CrudRepository<Account,Long> {

    public Account findByUsername(String username);

    }
}

当前回答

这对我很有用

上述测试类的包名被更改为与普通类的包名相同。

更改为这个

其他回答

在我的情况下,我使用了错误包中的Test类。 当我替换import org.junit.Test;导入org.junit.jupiter.api.Test;它工作。

检查一下是否重构了带有@SpringBootApplication注释的主类的包名是值得的。在这种情况下,测试用例应该在一个合适的包中,否则它将在旧的包中寻找它。这就是我的情况。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;



@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest
@AutoConfigureWebMvc
public class RepoTest {

    @Autowired
    private ThingShiftDetailsRepository thingShiftDetailsRepo;

    @Test
    public void findThingShiftDetails() {
            ShiftDetails details = new ShiftDetails();
            details.setThingId(1);

            thingShiftDetailsRepo.save(details);

            ShiftDetails dbDetails = thingShiftDetailsRepo.findByThingId(1);
            System.out.println(dbDetails);
    }
}

上面的注释对我来说效果很好。我使用spring boot与JPA。

对我来说 确保你的(测试包名)YourApplicationTests与(主包名)是等价的。

当所有的类都在同一个包中时,测试类就可以工作了。当我将所有java类移动到不同的包以保持正确的项目结构时,我得到了相同的错误。

我通过在测试类中提供我的主类名来解决它,如下所示。

@SpringBootTest(classes=JunitBasicsApplication.class)