【问题标题】:Can not Autowire bean in Junit无法在 Junit 中自动装配 bean
【发布时间】:2019-05-08 13:50:26
【问题描述】:

我正在尝试使用 Junit 对控制器类进行单元测试。但是,当我尝试自动装配我的扩展 crudRepository 的 PlayerRepository 接口时,它给出了这个错误:

2018-12-06 21:59:39.530 错误 8780 --- [主要] o.s.test.context.TestContextManager : 捕获异常同时 允许 TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@78e117e3] 准备测试实例 [edu.ceng.gameproject.player.PlayerControllerTest@4f704591]

(因为很长,我没有把整个错误写出来。)

它还说:

原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 'edu.ceng.gameproject.player.PlayerRepository' 类型的合格 bean 可用:预计至少有 1 个符合 autowire 条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

顺便说一句,我可以在我的控制器中进行自动装配以对数据库进行更改。它只是在测试中不起作用。这是我的代码:

控制器类:

@Controller    // This means that this class is a Controller
@RequestMapping(path="/Player") // This means URL's start with /Player 
(after Application path)

public class PlayerController {

 @Autowired 
 private PlayerRepository playerRepository;
}

这是 PlayerRepsitory 接口:

@Repository
public interface PlayerRepository extends CrudRepository<Player, String> {


}

我进行自动装配的抽象测试类:

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest(classes = Main.class)

 @WebAppConfiguration
 public abstract class GameProjectBackEndApplicationTests {

 protected MockMvc mvc;

 @Autowired
 WebApplicationContext webApplicationContext;

 @Autowired
 PlayerRepository playerRepository;


 protected void setUp() {
     mvc = 
  MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
 }

}

我使用自动装配 playerRepository 的 PlayerControllerTest 类:

public class PlayerControllerTest extends GameProjectBackEndApplicationTests 
{

    @Override
    @Before
    public void setUp() {
        super.setUp();
    }

    @Test
    public void test_getUsersList_withOk() throws Exception {
        String uri = "/Player/all";

        // Create user in the database
        Player createdUser = playerRepository.save(new Player("testUser", 
"testPassword"));

        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
                .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();

        // check if status is 200 - OK
        int status = mvcResult.getResponse().getStatus();
        assertEquals(200, status);

        String content = mvcResult.getResponse().getContentAsString();
        Player[] playerList = super.mapFromJson(content, Player[].class);

        // check if list has actually any user
        assertTrue(playerList.length > 0);


        // check returned list has user that we created
        boolean contains = false;
        for (int i = 0; i < playerList.length; i++) {
            if 
              (createdUser.getUsername().equals(playerList[i].getUsername())
                    && 
    createdUser.getPasswd().equals(playerList[i].getPasswd())) {
                contains = true;
            }
        }
        // assert there is a user that we created
        assertTrue(contains);
        //delete created user
        playerRepository.deleteById(createdUser.getUsername());
    }
}

提前致谢。

【问题讨论】:

  • 您是否尝试在您的TestClass 上添加@DataJpaTest?
  • 试过但没用。
  • 使用@MockBean 注入所需的依赖项。
  • 我应该如何使用@MockBean,你能更清楚一点吗?
  • 相关包有哪些?如果 PlayerControllerTest 所在的包不在定义 @Controller 的包处或之上,则 Spring 的默认自动检测将找不到您的控制器。在这种情况下,您需要明确告诉 Spring 哪些包要包含在扫描中,这可以通过注释轻松完成。如果这不是问题,我有第二个想法。

标签: java spring junit junit4


【解决方案1】:

正如我在 cmets 中所说,使用 @MockBean 为控制器中所需的每个依赖项注入一个模拟。您的测试类将如下所示。

 @RunWith(SpringRunner.class)
 @SpringBootTest(classes = Main.class)

 @WebAppConfiguration
 public class GameProjectBackEndApplicationTests {

     private MockMvc mvc;

     @Autowired
     private WebApplicationContext webApplicationContext;

     @MockBean
     private PlayerRepository playerRepository;

     @Before
     public void setUp() {
         mvc = 
         MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

         // Mock calls to PlayerRepository
         // Mockito.when(playerRepository.getEntries(1)).thenReturn(myList);
     }

     @Test
     public void myTest() {
      ....
     }

}

另外,我真的不建议您在测试中使用继承。最好将所有东西都放在一个地方。

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2022-01-03
    • 2020-10-22
    • 2016-09-27
    • 2015-07-05
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多