String name = "room";Room room = new Room(name);roomService.persist(room);assertThat(roomService.findByName(name), equalTo(room));assertNull(roomService.findByName("none"));
import static org.mockito.AdditionalAnswers.returnsFirstArg;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.when;
@Mockprivate MyClass myClass;
// this will return anything you pass, but it's pretty unrealisticwhen(myClass.myFunction(any())).then(returnsFirstArg());// it is more "life-like" to accept only the right typewhen(myClass.myFunction(any(ClassOfArgument.class))).then(returnsFirstArg());
myClass.my函数如下所示:
public class MyClass {public ClassOfArgument myFunction(ClassOfArgument argument){return argument;}}
@Testfun demo() {// mock a sample functionval aMock: (String) -> (String) = mockk()
// make it return the same as the argument on every invocationevery {aMock.invoke(any())} answers {firstArg()}
// test itassertEquals("senko", aMock.invoke("senko"))assertEquals("senko1", aMock.invoke("senko1"))assertNotEquals("not a senko", aMock.invoke("senko"))}