我想用签名模拟一个方法:
public <T> T documentToPojo(Document mongoDoc, Class<T> clazz)
Run Code Online (Sandbox Code Playgroud)
我嘲笑它如下:
Mockito.when(mongoUtil.documentToPojo(Mockito.any(Document.class), Mockito.any(WorkItemDTO.class)))
Run Code Online (Sandbox Code Playgroud)
但我得到的错误是:
documentToPojo(Document, Class<T>)类型中的方法MongoUtil不适用于参数(Document, WorkItemDTO)
Mockito有什么方法可以帮我模拟T吗?
我有以下代码
@RequestMapping(value = "admin/category/edit/{id}",method = RequestMethod.GET)
public String editForm(Model model,@PathVariable Long id) throws NotFoundException{
Category category=categoryService.findOne(id);
if(category==null){
throw new NotFoundException();
}
model.addAttribute("category", category);
return "edit";
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在抛出NotFoundException时进行单元测试,所以我编写这样的代码
@Test(expected = NotFoundException.class)
public void editFormNotFoundTest() throws Exception{
Mockito.when(categoryService.findOne(1L)).thenReturn(null);
mockMvc.perform(get("/admin/category/edit/{id}",1L));
}
Run Code Online (Sandbox Code Playgroud)
但失败了.有关如何测试异常的任何建议吗?
或者我应该在CategoryService中抛出异常,这样我就可以做这样的事情
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));
Run Code Online (Sandbox Code Playgroud) 您能否解释一下何时使用以下注释以及何时不使用这些注释。我对测试框架还很陌生,并且对网络上的所有答案感到困惑。
@Mock
private Resource resource;
@MockBean
private Resource resource;
@InjectMock
private ProductService productService;
@AutoWired
Private ProductRepository productRepo;
Run Code Online (Sandbox Code Playgroud) 我在Spring Framework上运行了几个集成测试,扩展了名为BaseITCase的基类.
像这样:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppCacheConfiguration.class, TestConfiguration.class}, loader = SpringBootContextLoader.class)
@Transactional
@WebMvcTest
public abstract class BaseITCase{...}
...
public class UserControllerTest extends BaseITCase {...}
Run Code Online (Sandbox Code Playgroud)
问题是其中一个测试有几个声明:@MockBean在它内部以及执行此测试的那一刻,Spring重新创建上下文,并且在此之后的测试有时使用错误的bean(来自为@的测试创建的上下文) MockBean).我通过检查bean有不同的哈希码来发现这一点.
当我使用@EventListener时,它变得非常关键.因为调用了错误上下文(已经完成执行的测试类的上下文)的侦听器,并且我在那里有错误的bean.
那有什么解决方法吗?
我试图将所有@MockBean声明移动到基本类,它工作正常,因为没有创建新的上下文.但是,它使基础课太重了.此外,我尝试为此测试创建一个脏上下文,但接下来的测试失败,并显示上下文已被关闭的消息.
我将 Spring Boot 用于我的 Web 应用程序,并使用 TestNG 进行单元测试。以下是我正在尝试的单元测试
@ContextConfiguration
public class AuthorizerTest extends AbstractTestNGSpringContextTests {
@InjectMocks
private Authorizer authorizer = new Authorizer();
@Mock
private PermissionRuleRepository permissionRuleRepository;
@BeforeMethod
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
@WithMockUser
public void testCheckPermission() throws Exception {
try {
authorizer.checkPermission(null, PermissionLevel.Type.ACCOUNT_OTHER);
fail();
} catch (AccessDeniedException ade) {
//
}
}
}
Run Code Online (Sandbox Code Playgroud)
authorizer.checkPermission内部使用SecurityContext来获取当前用户名。但在调试时,authentication对象是null. 不知道为什么使用时它没有被填充WithMockUser。
我只想知道JUnit测试中times(0)和never()之间的区别是什么.
例如,我有用于在mongoDB中保存数据的测试行代码:
verify(mockRepository,never()).save(any(User.class));
Run Code Online (Sandbox Code Playgroud)
如果我把它写成:
verify(mockRepository,times(0)).save(any(User.class));
Run Code Online (Sandbox Code Playgroud)
两个测试都显示save方法没有调用.(如果我错了,请纠正我)这两者有什么区别吗?
Im 辅助方法使用 ehcache,以减少对 Db 的查询。现在想实现JUnit+Mockito测试,确保ehcache正常工作。有这样的测试变体:
@Autowired
private DBService service;
@Autowired
private DiscountHelper discountHelper;
@Autowired
private CacheManager cacheManager;
@Before
public void setUp() throws Exception {
assertNotNull(cacheManager);
}
@Test
public void testGetDiscountWithCache() throws RuntimeException,
InterruptedException {
String id1 = "id1";
String id2 = "id2";
String id3 = "id3";
List<String> discountsId = new ArrayList<String>();
discountsId.add(id1);
discountsId.add(id2);
discountsId.add(id3);
List<Map<String, Object>> attrList = new ArrayList<Map<String, Object>>();
attrList.add(new Discount().getAttributes());
attrList.add(new Discount().getAttributes());
attrList.add(new Discount().getAttributes());
Cache cache = cacheManager.getCache(DiscountHelper.CACHE_NAME);
assertNotNull(cache);
assertEquals(0, cache.getSize());
// First run with empty cache …Run Code Online (Sandbox Code Playgroud) 我想在我的IT之一中使用Springockito模拟DAO bean。在我的IT中,我必须使用spring context.xml来自动装配某些服务,还必须使用mockApplication.xml来模拟DAO。因此,如何同时使用两个xml配置文件?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {"classpath*:/MockApplicationContext.xml"})
public class PayRollComponentFacadeIT {
@Autowired
IPayRollComponentFacade payRollComponentFacade;
@ReplaceWithMock
@Autowired
IPayRollPersistenceManager payRollPersistenceManager;
Run Code Online (Sandbox Code Playgroud)
我已经包括了模拟上下文 @ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {"classpath*:/MockApplicationContext.xml"})
但是我还必须包括春季背景 @ContextConfiguration(locations = {"classpath*:/testApplicationContext.xml"})
问候拉吉卜
我怎样才能在mockito,spring mvc环境中为boolean编写测试用例
例如,如下面的响应
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"name":"myName","DOB":"12345"}
Forwarded URL = null
Redirected URL = null
Cookies = []
Run Code Online (Sandbox Code Playgroud)
我们会写测试用例,比如
mockMvc.perform(get("/reqMapping/methodName"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name",comparesEqualTo("myName");
.andExpect(jsonPath("$.DOB",comparesEqualTo("12345");
Run Code Online (Sandbox Code Playgroud)
对?但是,当我们得到响应时,请遵循
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
**Body = true**
Forwarded URL = null
Redirected URL = null
Cookies = []
Run Code Online (Sandbox Code Playgroud)
我该如何编写测试用例?
mockMvc.perform(get("/reqMapping/methodName"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(???);
Run Code Online (Sandbox Code Playgroud) 我正在尝试针对 Spring Controller 运行单元测试:
@RunWith (SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration ({"classpath*:WEB-INF/spring/app-config.xml", "classpath*:WEB-INF/spring/mvc-config.xml",
"classpath*:WEB-INF/spring/security-config.xml"})
public class DashboardControllerTest extends BaseControllerTest
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
java.lang.NoSuchMethodError: org.springframework.core.CollectionFactory.createLinkedMapIfPossible(I)Ljava/util/Map;
Run Code Online (Sandbox Code Playgroud)
我发现了这个,它声称解决方案是不包括 Spring-mock。我不包括弹簧模拟。谁能告诉我在我的 pom 中是什么在拉 spring-mock 2.0.8?
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<name>Foo</name>
<description>Bar</description>
<artifactId>baz</artifactId>
<packaging>war</packaging>
<parent>
<groupId>com.be.bop</groupId>
<artifactId>baz</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<properties>
<compileSource>1.5</compileSource>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.1.4.RELEASE</org.springframework.version>
<org.springsecurity.version>3.2.5.RELEASE</org.springsecurity.version>
<spring.ldap.version>2.0.3.RELEASE</spring.ldap.version>
<spring.data.oracle.version>1.1.0.RELEASE</spring.data.oracle.version>
<org.springframework.ws.version>1.5.9</org.springframework.ws.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r07</version> …Run Code Online (Sandbox Code Playgroud) springmockito ×10
mockito ×6
java ×5
spring ×5
spring-mvc ×3
unit-testing ×3
junit ×2
spring-test ×2
ehcache ×1
maven ×1
mongodb-java ×1
testng ×1