无法在 Junit 中自动装配 bean
Can not Autowire bean in Junit
我正在尝试使用 Junit 对控制器 Class 进行单元测试。但是,当我尝试自动装配扩展了 crudRepository 的 PlayerRepository 接口时,它给出了这个错误:
2018-12-06 21:59:39.530 ERROR 8780 --- [ main]
o.s.test.context.TestContextManager : Caught exception while
allowing TestExecutionListener
[org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@78e117e3]
to prepare test instance
[edu.ceng.gameproject.player.PlayerControllerTest@4f704591]
(因为太长了,所以没有把错误全部放上去。)
它还说:
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'edu.ceng.gameproject.player.PlayerRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
顺便说一句,我可以在我的控制器中进行自动装配以对数据库进行更改。它只是在测试中不起作用。这是我的代码:
控制器Class:
@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> {
}
抽象测试 class 我在其中进行自动装配 :
@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();
}
}
PlayerControllerTest class 我使用自动装配的 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());
}
}
提前致谢。
正如我在评论中所说,使用 @MockBean
为控制器中所需的每个依赖项注入模拟。您的测试 class 将如下所示。
@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() {
....
}
}
另外,我真的不建议在测试中使用继承。最好把所有东西都放在一个地方。
我正在尝试使用 Junit 对控制器 Class 进行单元测试。但是,当我尝试自动装配扩展了 crudRepository 的 PlayerRepository 接口时,它给出了这个错误:
2018-12-06 21:59:39.530 ERROR 8780 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@78e117e3] to prepare test instance [edu.ceng.gameproject.player.PlayerControllerTest@4f704591]
(因为太长了,所以没有把错误全部放上去。)
它还说:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.ceng.gameproject.player.PlayerRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
顺便说一句,我可以在我的控制器中进行自动装配以对数据库进行更改。它只是在测试中不起作用。这是我的代码:
控制器Class:
@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> {
}
抽象测试 class 我在其中进行自动装配 :
@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();
}
}
PlayerControllerTest class 我使用自动装配的 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());
}
}
提前致谢。
正如我在评论中所说,使用 @MockBean
为控制器中所需的每个依赖项注入模拟。您的测试 class 将如下所示。
@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() {
....
}
}
另外,我真的不建议在测试中使用继承。最好把所有东西都放在一个地方。