- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有两个 Controller ,如下所示,我一直在尝试为它们编写测试用例,但由于 Controller 用户@AuthenticationPrincipal。我很难为他们编写测试用例,并且在运行测试用例时遇到错误。
@ResponseBody
@RequestMapping(value = "/view/{id}", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity renderDocument(@AuthenticationPrincipal Principal principal, @PathVariable("id") Long id)
throws IOException {
Journal journal = journalRepository.findOne(id);
Category category = journal.getCategory();
CurrentUser activeUser = (CurrentUser) ((Authentication) principal).getPrincipal();
User user = userRepository.findOne(activeUser.getUser().getId());
List<Subscription> subscriptions = user.getSubscriptions();
Optional<Subscription> subscription = subscriptions.stream()
.filter(s -> s.getCategory().getId().equals(category.getId())).findFirst();
if (subscription.isPresent() || journal.getPublisher().getId().equals(user.getId())) {
File file = new File(PublisherController.getFileName(journal.getPublisher().getId(), journal.getUuid()));
InputStream in = new FileInputStream(file);
return ResponseEntity.ok(IOUtils.toByteArray(in));
} else {
return ResponseEntity.notFound().build();
}
}
@RequestMapping(method = RequestMethod.POST, value = "/publisher/publish")
@PreAuthorize("hasRole('PUBLISHER')")
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("category")Long categoryId, @RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, @AuthenticationPrincipal Principal principal) {
CurrentUser activeUser = (CurrentUser) ((Authentication) principal).getPrincipal();
Optional<Publisher> publisher = publisherRepository.findByUser(activeUser.getUser());
String uuid = UUID.randomUUID().toString();
File dir = new File(getDirectory(publisher.get().getId()));
createDirectoryIfNotExist(dir);
File f = new File(getFileName(publisher.get().getId(), uuid));
if (!file.isEmpty()) {
try {
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
FileCopyUtils.copy(file.getInputStream(), stream);
stream.close();
Journal journal = new Journal();
journal.setUuid(uuid);
journal.setName(name);
journalService.publish(publisher.get(), journal, categoryId);
return "redirect:/publisher/browse";
} catch (Exception e) {
redirectAttributes.addFlashAttribute("message",
"You failed to publish " + name + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + name + " because the file was empty");
}
return "redirect:/publisher/publish";
}
测试用例是
@Test
@WithMockUser(username = "user1", roles = { "USER" })
public void renderDocument() throws Exception {
mockMvc.perform(get("/view/{id}", 1)).andExpect(content().contentType(contentType)).andExpect(status().isOk());
}
但是我收到以下错误:-
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.crossover.trial.journals.model.Publisher_$$_jvst650_0.toString(Publisher_$$_jvst650_0.java)
at org.springframework.web.util.UriComponents.getVariableValueAsString(UriComponents.java:269)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:234)
at org.springframework.web.util.HierarchicalUriComponents$FullPathComponent.expand(HierarchicalUriComponents.java:685)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:328)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:47)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:163)
at org.springframework.web.util.UriComponentsBuilder.buildAndExpand(UriComponentsBuilder.java:412)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.<init>(MockHttpServletRequestBuilder.java:122)
at org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get(MockMvcRequestBuilders.java:55)
at com.crossover.trial.journals.rest.JournalServiceTest.renderDocument(JournalServiceTest.java:187)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
JournalServiceTest.java
package com.crossover.trial.journals.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Optional;
import com.crossover.trial.journals.Application;
import com.crossover.trial.journals.model.Journal;
import com.crossover.trial.journals.model.Publisher;
import com.crossover.trial.journals.model.User;
import com.crossover.trial.journals.repository.PublisherRepository;
import com.crossover.trial.journals.service.JournalService;
import com.crossover.trial.journals.service.ServiceException;
import com.crossover.trial.journals.service.UserService;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JournalServiceTest {
private final static String NEW_JOURNAL_NAME = "New Journal";
@Autowired
private JournalService journalService;
@Autowired
private UserService userService;
@Autowired
private PublisherRepository publisherRepository;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
}
@Test
public void browseSubscribedUser() {
List<Journal> journals = journalService.listAll(getUser("user1"));
assertNotNull(journals);
assertEquals(1, journals.size());
assertEquals(new Long(1), journals.get(0).getId());
assertEquals("Medicine", journals.get(0).getName());
assertEquals(new Long(1), journals.get(0).getPublisher().getId());
assertNotNull(journals.get(0).getPublishDate());
}
@Test
public void browseUnSubscribedUser() {
List<Journal> journals = journalService.listAll(getUser("user2"));
assertEquals(0, journals.size());
}
@Test
public void listPublisher() {
User user = getUser("publisher1");
Optional<Publisher> p = publisherRepository.findByUser(user);
List<Journal> journals = journalService.publisherList(p.get());
assertEquals(2, journals.size());
assertEquals(new Long(1), journals.get(0).getId());
assertEquals(new Long(2), journals.get(1).getId());
assertEquals("Medicine", journals.get(0).getName());
assertEquals("Test Journal", journals.get(1).getName());
journals.stream().forEach(j -> assertNotNull(j.getPublishDate()));
journals.stream().forEach(j -> assertEquals(new Long(1), j.getPublisher().getId()));
}
@Test(expected = ServiceException.class)
public void publishFail() throws ServiceException {
User user = getUser("publisher2");
Optional<Publisher> p = publisherRepository.findByUser(user);
Journal journal = new Journal();
journal.setName("New Journal");
journalService.publish(p.get(), journal, 1L);
}
@Test(expected = ServiceException.class)
public void publishFail2() throws ServiceException {
User user = getUser("publisher2");
Optional<Publisher> p = publisherRepository.findByUser(user);
Journal journal = new Journal();
journal.setName("New Journal");
journalService.publish(p.get(), journal, 150L);
}
@Test()
public void publishSuccess() {
User user = getUser("publisher2");
Optional<Publisher> p = publisherRepository.findByUser(user);
Journal journal = new Journal();
journal.setName(NEW_JOURNAL_NAME);
journal.setUuid("SOME_EXTERNAL_ID");
try {
journalService.publish(p.get(), journal, 3L);
} catch (ServiceException e) {
fail(e.getMessage());
}
List<Journal> journals = journalService.listAll(getUser("user1"));
assertEquals(2, journals.size());
journals = journalService.publisherList(p.get());
assertEquals(2, journals.size());
assertEquals(new Long(3), journals.get(0).getId());
assertEquals(new Long(4), journals.get(1).getId());
assertEquals("Health", journals.get(0).getName());
assertEquals(NEW_JOURNAL_NAME, journals.get(1).getName());
journals.stream().forEach(j -> assertNotNull(j.getPublishDate()));
journals.stream().forEach(j -> assertEquals(new Long(2), j.getPublisher().getId()));
}
@Test(expected = ServiceException.class)
public void unPublishFail() {
User user = getUser("publisher1");
Optional<Publisher> p = publisherRepository.findByUser(user);
journalService.unPublish(p.get(), 4L);
}
@Test(expected = ServiceException.class)
public void unPublishFail2() {
User user = getUser("publisher1");
Optional<Publisher> p = publisherRepository.findByUser(user);
journalService.unPublish(p.get(), 100L);
}
@Test
public void unPublishSuccess() {
User user = getUser("publisher2");
Optional<Publisher> p = publisherRepository.findByUser(user);
journalService.unPublish(p.get(), 4L);
List<Journal> journals = journalService.publisherList(p.get());
assertEquals(1, journals.size());
journals = journalService.listAll(getUser("user1"));
assertEquals(1, journals.size());
}
@Test
public void renderDocument() throws Exception {
mockMvc.perform(get("/view/{id}", "1"));
}
protected User getUser(String name) {
Optional<User> user = userService.getUserByLoginName(name);
if (!user.isPresent()) {
fail("user1 doesn't exist");
}
return user.get();
}
}
最佳答案
您已经从数据库中获取了对象,如下所示,
Journal journal = journalRepository.findOne(id);
Category category = journal.getCategory();
以及你曾经使用过的地方
category.getId()
说明:当您从数据库中提取日记对象时,只会与代理类别对象一起提取日记对象,而不是实际的类别对象。因此,当您尝试使用日志对象获取类别时,它会尝试使用实际类别对象初始化代理类别对象,这需要数据库调用。
但是由于日志对象可能与 session 分离,因此它显示没有 session 。
解决方案:你有代理对象,有很多方法可以解开代理对象
categoryProxyObj=entityManager.unwrap(SessionImplementor.class).getPersistenceContext().unproxy(categoryProxyObj);
categoryProxyObj=((SessionImplementor)session).getPersistenceContext().unproxy(categoryProxyObj);
Hibernate.initialize(categoryProxyObj);
if (categoryProxyObj instanceof HibernateProxy) {
CategoryProxyObj=((HibernateProxy)categoryProxyObj).getHibernateLazyInitializer().getImplementation();
}
无论您喜欢哪种方法,都可以使用。
或者,如果您不需要类别对象,而只需要类别 ID,则在 Journal 中
使用
private Category category;
@OneToOne(fetch=FetchType.LAZY, optional=false)
public Category getCategory() {
return this.category;
}
而不是
@OneToOne(fetch=FetchType.LAZY, optional=false)
private Category category;
关于java - org.hibernate.LazyInitializationException : could not initialize proxy - no Session . 对于测试用例 JUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41695551/
我正在尝试将 keras.initializers 引入我的网络,following this link : import keras from keras.optimizers import RMS
我正在为程序创建某种前端。为了启动程序,我使用了调用 CreateProcess(),其中接收到一个指向 STARTUPINFO 结构的指针。初始化我曾经做过的结构: STARTUPINFO star
我已经模板化了 gray_code 类,该类旨在存储一些无符号整数,其基础位以格雷码顺序存储。这里是: template struct gray_code { static_assert(st
我已经查看了之前所有与此标题类似的问题,但我找不到解决方案。所有错误都表明我没有初始化 ArrayList。我是否没有像 = new ArrayList 这样初始化 ArrayList? ? impo
当涉及到 Swift 类时,我对必需的初始化器和委托(delegate)的初始化器有点混淆。 正如您在下面的示例代码中所见,NewDog 可以通过两种方式中的一种进行初始化。如您所见,您可以通过在初始
几天来我一直在为一段代码苦苦挣扎。我在运行代码时收到的错误消息是: 错误:数组初始值设定项必须是初始值设定项列表 accountStore(int size = 0):accts(大小){} 这里似乎
我想返回一个数组,因为它是否被覆盖并不重要,我的方法是这样的: double * kryds(double linje_1[], double linje_2[]){ double x = linje
尝试在 C++ 中创建一个简单的 vector 时,出现以下错误: Non-aggregates cannot be initialized with initializer list. 我使用的代码
如何在构造函数中(在堆栈上)存储初始化列表所需的临时状态? 例如,实现这个构造函数…… // configabstraction.h #include class ConfigAbstraction
我正在尝试编写一个 native Node 插件,它枚举 Windows 机器上的所有窗口并将它们的标题数组返回给 JS userland。 但是我被这个错误难住了: C:\Program Files
#include using namespace std; struct TDate { int day, month, year; void Readfromkb() {
我很难弄清楚这段代码为何有效。我不应该收到“数组初始值设定项必须是初始值设定项列表”错误吗? #include class B { public: B() { std::cout << "B C
std::map m = { {"Marc G.", 123}, {"Zulija N.", 456}, {"John D.", 369} }; 在 Xcode 中,我将 C+
为了帮助你明白这一点,我给出了我的代码:(main.cpp),只涉及一个文件。 #include #include using namespace std; class test{ public
这在 VS2018 中有效,但在 2008 中无效,我不确定如何修复它。 #include #include int main() { std::map myMap = {
我有一个类: #include class Object { std::shared_ptr object_ptr; public: Object() {} template
我正在为 POD、STL 和复合类型(如数组)开发小型(漂亮)打印机。在这样做的同时,我也在摆弄初始化列表并遇到以下声明 std::vector arr{ { 10, 11, 12 }, { 20,
我正在使用解析实现模型。 这是我的代码。 import Foundation import UIKit import Parse class User { var objectId : String
我正在观看 Java 内存模型视频演示,作者说与 Lazy Initialization 相比,使用 Static Lazy Initialization 更好,我不清楚他说的是什么想说。 我想接触社
如果您查看 Backbone.js 的源代码,您会看到此模式的多种用途: this.initialize.apply(this, arguments); 例如,这里: var Router =
我是一名优秀的程序员,十分优秀!