我想传递我模拟的方法的参数来返回值
例子:
when(mockedObject.printEntries(anyLong()).thenReturn("%d entries");
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这一目标?
我正在尝试使用 Mockito 和 PowerMockito 设置单元测试,但它抛出:
线程“main”中的异常 java.lang.NoClassDefFoundError: org/mockito/exceptions/Reporter
每当我尝试运行测试时。这些是我的依赖项:
testCompile 'org.mockito:mockito-core:2.8.9'
testCompile 'org.powermock:powermock-api-mockito2:1.6.5'
testCompile 'org.powermock:powermock-module-junit4:1.7.4'
Run Code Online (Sandbox Code Playgroud)
有谁知道如何修理它?
我正在获取对象的集合,并尝试在 @ManyToOne 关系中使用延迟加载来获取对象。但是,当我调用服务方法时,集合中的对象获得 NULL 值
List<Location> all = locationRepository.getLocations(ids);
Merchant merchant = all.get(0).getMerchant();
// merchant == null
Run Code Online (Sandbox Code Playgroud)
LocationRepository.java
@Repository
public interface LocationRepository extends JpaRepository<Location, String> {
@Query(value = "SELECT * FROM b_location WHERE id IN :ids", nativeQuery = true)
List<Location> getLocations(@Param("ids") Set<String> ids);
}
Run Code Online (Sandbox Code Playgroud)
位置.java
@Entity
@Table(name = "b_location")
public class Location {
@Id
@Column(name = "id")
private String id;
@Column(name = "merchant_id", nullable = false)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Long merchantId;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "merchant_id", referencedColumnName = "id", …
Run Code Online (Sandbox Code Playgroud) 我在这里尝试测试以下代码:
public class Something {
public String doSomething(MyClass myClass) {
return Utils.getPresentationString(myClass)
}
}
public class Utils{
public static String getPresentationString(MyClass myClass) {
if (myClass instanceof MySubClass) {
MySubClass mySubClass = (MySubClass) myClass;
return mySubClass.getMaskedPresentationString();
} else {
return myClass.getPresentationString();
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于Utils是静态的,因此我在测试Something类时以黑盒方式对其进行了测试。
我试图让这行代码返回一个模拟:
MySubClass mySubClass = (MySubClass) myClass;
Run Code Online (Sandbox Code Playgroud)
所以我可以做
doReturn(MY_MASKED_STRING).when(this.mySubClassMock).getMaskedPresentationString()
Run Code Online (Sandbox Code Playgroud)
然后做
assertEquals(MY_MASKED_STRING, this.somethingUnderTest.doSomething(this.myClassMock))
Run Code Online (Sandbox Code Playgroud)
我该如何做这样的工作
doReturn(this.mySubClassMock).when(this.myClassMock).<<cast to MySubClass.class>>
Run Code Online (Sandbox Code Playgroud) JPQL 是否有可能返回所有结果并忽略参数中的空值而不是查找空值?
例如:
@Query("SELECT p FROM PromoCode p " +
"WHERE (LOWER(p.name) LIKE LOWER(concat('%', concat(:query, '%'))) OR " +
"LOWER(p.promoCode) LIKE LOWER(concat('%', concat(:query, '%')))) AND p.type = :type")
Page<PromoCode> search(@Param("query") String query, @Param("type") PromoCode.Type type, Pageable pageable)
Run Code Online (Sandbox Code Playgroud)
如果它为空,我如何忽略:type
它?
我正在使用Resteasy服务器端模拟框架来测试我的服务.我不想测试业务逻辑,但我想测试服务生成的数据.
使用这种方法,我可以创建一个简单的测试.但是,在我的RestEasy服务中,我有一些依赖,我想嘲笑.
请参阅以下我要测试的示例服务.必须嘲笑协作者,以便测试服务.
@Path("v1")
Class ExampleService {
@inject
private Collaborator collaborator;
@GET
@Path("/")
@Produces({ "application/xml", "application/json" })
public Response getDummy() throws WSAccessException, JsonParseException, JsonMappingException, IOException {
...
Result result = collaborator.getResult();
..
return Response.ok("helloworld").build();
}
}
Run Code Online (Sandbox Code Playgroud)
junit测试如下
@Test
public void testfetchHistory() throws URISyntaxException {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
POJOResourceFactory noDefaults = new POJOResourceFactory(ExampleService.class);
dispatcher.getRegistry().addResourceFactory(noDefaults);
MockHttpRequest request = MockHttpRequest.get("v1/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(..);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在测试中嘲笑合作者?
因此,我对代码进行了一些分解,使其更通用,也更容易让其他人理解类似的问题
这是我的主要代码:
protected void methodA(String name) {
Invocation.Builder requestBuilder = webTarget.request();
requestBuilder.header(HttpHeaders.AUTHORIZATION, authent.getPassword());
response = request.invoke();
if (response.equals("unsuccessfull")) {
log.warn("warning blabla: {} ({})");
} else {
log.info("info blabla {}");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
而我的测试代码如下所示:
@Test
public void testMethodA() throws Exception {
final String name = "testName";
this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
assertEquals(1, logger.infos.size());
}
Run Code Online (Sandbox Code Playgroud)
正如我所说,代码更复杂,我将其分解并使其更短......希望它仍然可读。
我的问题不是我的when().thenReturn()
代码不起作用,因此我的代码无法进一步进行......我想我的模拟由于某种原因无法正常工作。
以下陈述的作用如下:
// The question is about the arguments being passed in the function.
SomeReturnOutput = CallSomeFunction(with(any(Long.class)), with(any(List.class)));
Run Code Online (Sandbox Code Playgroud)
我试着寻找它,但找不到令人满意的答案.什么with(any(Long.class))
和with(any(List.class))
返回?
我以为我理解了两者之间的区别@Mock
,@MockBean
甚至我认为任何被模拟的对象都不会调用真正的方法,尽管当我在测试下运行时,我可以看到篮子已插入到 hsqldb 日志中。所以现在我对为什么@Mock
使用时插入篮子而使用时不插入篮子感到有些困惑@MockBean
。
INSERT INTO BASKET VALUES(5,'ABCDEFGHIJ','ACTIVE',1,'2019-01-18 12:00:36.066000','2019-01-18 12:00:36.066000')
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我这样做,那么 hsqldb 是干净的。在这两种情况下测试都是成功的。
@MockBean
private BasketRepository basketRepo;
Run Code Online (Sandbox Code Playgroud)
测试班
@RunWith( SpringRunner.class )
@SpringBootTest( )
@ActiveProfiles( "test" )
public class BasketServiceTests
{
@SpyBean
private BasketService basketService;
@Mock
private BasketRepository basketRepo;
@Autowired
private UserAccountRepository userAccountRepo;
@Test
public void createBasketWithSameOrderRef() throws Exception
{
UserAccount customer = userAccountRepo.findById( 1 )
.orElseThrow( () -> new NotFoundException( "Customer not found" ) );
Basket basket = new Basket();
basket.setAudit( new Audit() …
Run Code Online (Sandbox Code Playgroud) 我有一个 Oracle 18.4.0 XE 数据库,我试图从 Hibernate 5.2.17 实现的 JPA 2.1 访问它。
我有ManyToMany
两个实体之间的连接:
public class PermissionEntity implements Serializable {
private static final long serialVersionUID = -3862680194592486778L;
@Id
@GeneratedValue
private Long id;
@Column(unique = true)
private String permission;
@ManyToMany
private List<RoleEntity> roles;
}
Run Code Online (Sandbox Code Playgroud)
public class RoleEntity implements Serializable {
private static final long serialVersionUID = 8037069621015090165L;
@Column(unique = true)
private String name;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
private List<PermissionEntity> permissions;
}
Run Code Online (Sandbox Code Playgroud)
尝试在 …
我正在尝试将 JUnit 5 集成到 Eclipse Oxygen3 下。该项目已经有 Mockito 2。
我已经完成了https://www.baeldung.com/mockito-junit-5-extension 中建议的所有步骤,如下所示:
依赖项:
代码:
public class Jupiter {
public boolean isAlpha() {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import java.util.Date;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class JupiterTest {
@InjectMocks
private Jupiter jupiter;
@BeforeEach
public void setup() …
Run Code Online (Sandbox Code Playgroud)