我正在尝试使用 Junit 对 Controller 类进行单元测试。但是,当我尝试 Autowiring 我的 PlayerRepository 接口(interface)(它扩展了 crudRepository)时,它给出了以下错误:
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)}
顺便说一句,我可以在 Controller 中进行 Autowiring 以对数据库进行更改。它只是在测试中不起作用。这是我的代码:
Controller 类:
@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> {
}
我进行 Autowiring 的抽象测试类:
@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();
}
}
我使用 Autowiring 的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());
}
}
提前致谢。
最佳答案
正如我在评论中所说,使用 @MockBean
为 Controller 中所需的每个依赖项注入(inject)模拟。您的测试类将如下所示。
@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() {
....
}
}
此外,我真的不建议在测试中使用继承。最好将所有内容集中在一处。
关于java - 无法在 Junit 中 Autowiring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658631/