我正在使用Spring MVC(3.2.2)和GAE(1.7.7)开发一个应用程序,我在LocalDatastoreServiceTestConfig和我的JUnit测试中遇到了一些问题。我在使用时有很多服务层单元测试工作正常...
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
@Before
public void setUp() throws Exception
{
helper.setUp();
}
public void tearDown() throws Exception
{
helper.tearDown();
}
然后我创建了一些旨在测试Spring MVC控制器的测试,例如以下......
@Controller
@RequestMapping("/users")
public class UserController
{
@Autowired
private UserService userService;
@RequestMapping(value="/user/{userName}",method=RequestMethod.GET, produces="application/json")
public @ResponseBody User getUser(@PathVariable String userName)
{
return this.userService.getUser(userName);
}
}
我的测试看起来如下......
@Test
public void testGetUser() throws Exception
{
User user = new User();
//create user object and save to db...
//check that it's been created
user = this.userService.getUser(userIdOne);
assertNotNull(user);
///other asserts...
this.mockMvc.perform(get("/users/user/"+user.getId()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
不幸的是,这似乎不起作用,因为控制器(getUser)方法中的代码找不到在调用之前创建和检索的用户。
经过一些调查后,我发现了一些帖子,讨论了本地GAE数据源和多线程的问题。问题是来自本地数据源的数据在其他线程上不可用。通过在您正在使用的所有线程上调用APIProxy.setEnvironmentForCurrentThread来解决此问题。我怀疑这是我在这里面临的问题(即mockmvc代码正在创建一个单独的线程)但是我无法在不更改非测试代码的情况下解决此问题。
有没有人遇到这个或有任何建议?提前致谢。
答案 0 :(得分:0)
我很确定在过去我做过类似的测试时,不会有另一个线程在起作用。但是,您可以轻松地在控制器中设置断点并从调用堆栈中确认。
我建议这样做,并检查一下,以及userService和userName是否符合预期。
我过去注意到的一件事是mockMvc期望设置@Pathvariable名称。
@Pathvariable("userName") String userName
要检查的另一件事是你没有通过一些申请百分比来模拟HRD。但是,您发布的代码似乎并非如此,并且您可以在测试中检索用户。