无法在Junit中自动装配bean

时间:2018-12-06 19:47:54

标签: java spring junit junit4

我正在尝试对Junit的Controller类进行单元测试。但是,当我尝试自动连接扩展了crudRepository的PlayerRepository接口时,会出现以下错误:

  

2018-12-06 21:59:39.530错误8780 --- [main]   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个符合自动装配条件的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());
    }
}

谢谢。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,使用@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() {
      ....
     }

}

此外,我不建议在测试中使用继承。最好将所有内容都放在一个地方。