不能在junit中自动连接bean

l2osamch  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(320)

我正在尝试用junit对控制器类进行单元测试。但是,当我尝试自动连接我的playerrepository接口(它扩展了crudepository)时,会出现以下错误:
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个符合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;
}

以下是playerRepository接口:

@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();
 }

}

PlayerController测试类,其中我使用autowired playerrepository:

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());
    }
}

提前谢谢。

a1o7rhls

a1o7rhls1#

如我在评论中所说,使用 @MockBean 为控制器中所需的每个依赖项注入一个mock。你的测试课是这样的。

@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() {
      ....
     }

}

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

相关问题