Search Results

Search found 34 results on 2 pages for 'mockito'.

Page 1/2 | 1 2  | Next Page >

  • Mockito verify no more interactions but omit getters

    - by michael lucas
    Mockito api provides method: Mockito.verifyNoMoreInteractions(someMock); but is it possible in Mockito to declare that I don't want more interactions with a given mock with the exceptions of interactions with its getter methods? The simple scenario is the one in which I test that sut changes only certain properties of a given mock and lefts other properties untapped. In example I want to test that UserActivationService changes property Active on an instance of class User but does't do anything to properties like Role, Password, AccountBalance, etc. I'm open to criticism regarding my approach to the problem.

    Read the article

  • Mockito upgrade causes null pointer problems

    - by Ann Addicks
    We upgraded from mockito-all-1.8.5.jar to mockito-all-1.9.0.jar and now see null pointers when using annotations for the classes being mocked. Here is an example: @Mock private static IAccountManager accountManager; @Mock private static IBusinessUnitManager businessUnitManager; private static Gson parser; @InjectMocks private static DownloadController downloadController; @BeforeClass public static void setUpBeforeClass() throws Exception { parser = new Gson(); downloadController = new DownloadController(accountManager, businessUnitManager, parser); } @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); Mockito.reset(accountManager, businessUnitManager); } As soon as accountManager is referenced in the download controller, it throws a npe. This worked in 1.8.5.

    Read the article

  • PowerMock Mockito static methods

    - by anergy
    Do we need to mock all static methods of a class when using PowerMock (with Mockito)? I mean, suppose we have: class MockMe { public static MockMe getInstance(){ //return new Instance via complex process; } public static List<X> anotherStaticMethod(){ // does xyz } } My question, if I need to mock getInstance method, is it necessary to mock "anotherStaticMethod" as well? PowerMock version:1.3, Mockito version:1.8

    Read the article

  • Easymock vs Mockito: Design vs Maintainability?

    - by RAbraham
    One way of thinking about this is: if we care about the Design of the code then Easymock is the better choice as it gives feedback to you by its concept of expectations If we care about the maintainability of tests( easier to read,write and having less brittle tests which are not affected much by change), then Mockito seems a better choice. My question is: - If you have used Easymock in large scale projects, do you find that your tests are harder to maintain? - What are the limitations of Mockito( other than endo testing)

    Read the article

  • Injecting Mockito mocks into a Spring bean

    - by teabot
    I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields. I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing. I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails: <bean id="dao" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="com.package.Dao" /> </bean> The error I currently encounter is as follows: ... Caused by: org...NoSuchBeanDefinitionException: No matching bean of type [com.package.Dao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: { @org...Autowired(required=true), @org...Qualifier(value=dao) } at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901) at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770) If I set the constructor-arg value to something invalid no error occurs when starting the application context.

    Read the article

  • Speed up compilation with mockito on Android

    - by pbreault
    I am currently developing an android app in eclipse using: One project for the app One project for the tests (Instrumentation and Pojo tests) In the test project, I am importing the mockito library for standard POJO testing. However, when I import the library, the compilation time skyrockets from 1 second to about 30 seconds in eclipse. The cause seems to be that the whole library is converted each time. So basically, each time a make a modification that I want to test, I have to wait 30 seconds. The only workarounds that I have found so far would be: Disable "Build Automatically" Create a project that includes only pojo tests and put mockito only there. Use another library that compiles faster (e.g. easymock) Any other suggestion?

    Read the article

  • How to mock a String using mockito?

    - by Alceu Costa
    I need to simulate a test scenario in which I call the getBytes() method of a String object and I get an UnsupportedEncodingException. I have tried to achieve that using the following code: String nonEncodedString = mock(String.class); when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error.")); The problem is that when I run my test case I get a MockitoException that says that I can't mock a java.lang.String class. Is there a way to mock a String object using mockito or, alternatively, a way to make my String object throw an UnsupportedEncodingException when I call the getBytes method? Here are more details to illustrate the problem: This is the class that I want to test: public final class A{ public static String f(String str){ try{ return new String(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // This is the catch block that I want to exercise. ... } } } This is my testing class (I'm using JUnit 4 and mockito): public class TestA { @Test(expected=UnsupportedEncodingException.class) public void test(){ String aString = mock(String.class); when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error.")); A.f(aString); } }

    Read the article

  • Configure autocomplete in intellij with hamcrest and mockito dsl

    - by sgargan
    I'm wondering if its possible to configure Intellij's smart insert to suggest hamcrest and mockito dsl idioms when in test classes. Really I'm looking for something like eclipse's 'static favorites', so that when I hit ctrl + space or ctrl +shift +space the idioms are present. In general is it possible to configure autocomplete/smart insert or the suggestions balloon for that matter. I've looked through the settings without much luck but could easily have overlooked something.

    Read the article

  • Creating a Serializable mock with Mockito error

    - by KwintenP
    I'm trying to create a mock object with Mockito that can be serialized. The object is an interface implementation. When this method is called, I receive an object that I want to pass to another object, hence using the doAnswer(...)-method. This is my code. InterfaceClass obj = mock(InterfaceClass.class, withSettings().serializable()); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); //Here I do something with the arguments } }).when(obj).someMethod( any(someObject.class)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(obj); byte[] yourBytes = bos.toByteArray(); } finally { out.close(); bos.close(); } As far as I can tell this should be correct (I'm fairly new to Mockito). But when Serializing my object I get this error: java.io.NotSerializableException: com.trust1t.ocs.signcore.test.InvalidInputTestCase$1 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1165) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at java.util.concurrent.ConcurrentLinkedQueue.writeObject(ConcurrentLinkedQueue.java:644) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at java.util.LinkedList.writeObject(LinkedList.java:943) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at com.trust1t.ocs.signcore.test.InvalidInputTestCase.certificateValidationTest(InvalidInputTestCase.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) The invalidInputTestCase class is the class containing the test where I'm using this code. It looks as if the mock object references this TestCase somewhere (can't find it though). Am I not correctly implementing this or better ideas to mock?

    Read the article

  • How to properly match varargs in Mockito

    - by qualidafial
    I've been trying to get to mock a method with vararg parameters using Mockito: interface A { B b(int x, int y, C... c); } A a = mock(A.class); B b = mock(B.class); when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b); assertEquals(b, a.b(1, 2)); This doesn't work, however if I do this instead: when(a.b(anyInt(), anyInt())).thenReturn(b); assertEquals(b, a.b(1, 2)); This works, despite that I have completely omitted the varargs argument when stubbing the method. Any clues?

    Read the article

  • mockito mock a constructor with parameter

    - by Shengjie
    I have a class as below: public class A { public A(String test) { bla bla bla } public String check() { bla bla bla } } The logic in the constructor A(String test) and check() are the things I am trying to mock. I want any calls like: new A($$$any string$$$).check() returns a dummy string "test". I tried: A a = mock(A.class); when(a.check()).thenReturn("test"); String test = a.check(); // to this point, everything works. test shows as "tests" whenNew(A.class).withArguments(Matchers.anyString()).thenReturn(rk); // also tried: //whenNew(A.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(rk); new A("random string").check(); // this doesn't work But it doesn't seem to be working. new A($$$any string$$$).check() is still going through the constructor logic instead of fetch the mocked object of A.

    Read the article

  • mockito ArrayList<String> problem...

    - by Sardathrion
    I have a method that I am trying to unit test. This method takes a parameter as an ArrayList and does things with it. The mock I am trying to define is: ArrayList<String> mocked = mock(ArrayList.class); which gives a [unchecked] unchecked conversion" warning. ArrayList<String> mocked = mock(ArrayList<String>.class); gives me an error. Anyone care to enlighten me as to what I am doing wrong?

    Read the article

  • Testing local scoped object with mockito without refactoring

    - by supertonsky
    Say I have the following code: public class ClassToTest { AnotherClass anotherClass; public void methodToTest( int x, int y ) { int z = x + y anotherClass.receiveSomething( z ); } } public class AnotherClass { public void receiveSomething( int z ) {.. do something.. } } I want to make assertion on the value of the variable z. How do I do this? Variables x, y, and z could be some other Java class types, and I just used "int" for simplicity.

    Read the article

  • Error while using PowerMockito.whenNew()

    - by Ankush
    I am using PowerMockito(1.3.6) with Mockito(1.8.3) and Junit(4.7) for testing. I am quite stuck on an error: [junit] Testcase: testNextPNRFromQueueHappyPath(com.orbitz.galileo.host.robot.GalpoQueueConnectionTest): Caused an ERROR [junit] org/mockito/internal/IMockHandler [junit] java.lang.NoClassDefFoundError: org/mockito/internal/IMockHandler [junit] at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.createNewSubsituteMock(DefaultConstructorExpectationSetup.java:80) [junit] at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.withArguments(DefaultConstructorExpectationSetup.java:48) [junit] at com.orbitz.galileo.host.robot.GalpoQueueConnectionTest.testNextPNRFromQueueHappyPath(GalpoQueueConnectionTest.java:62) [junit] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [junit] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [junit] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) My class under test : GalpoQueueConnection is basically creating a new object of another class : QueueReadBuilder. I am trying to do something like: @RunWith(PowerMockRunner.class) @PrepareForTest({GalpoQueueConnection.class, ApolloProcUtils.class}) public class GalpoQueueConnectionTest extends TestCase{ @Test public void testNextPNRFromQueueHappyPath() throws Exception { QueueReadBuilder mockBuilder = mock(QueueReadBuilder.class); PowerMockito.whenNew(QueueReadBuilder.class).withArguments(anyString(), anyString(), anyString()).thenReturn(mockBuilder); } } It seems like somehow powermockito is trying to call IMockHandler, and I looked at Mockito 1.8.3 api, and there isn't any. Any suggestions/ clues would be welcome.

    Read the article

  • GWT and Mock the view in MVP pattern

    - by Yannick Eurin
    Hello, i dunno if the question is already ask, but i couldn't find it... i'm searching a way to mock my view in order to test my presenter ? i try to use mockito for the view, and set it in the presenter, but in result in presenter, when i call presenter.getDisplay() (the getter for the view) all of my widget is null ? as i believe it's normal mockito will not mock the widget. i'm 100% sure i mistaken something but i couldnt find it. thanks for your enlightement :)

    Read the article

  • How can I use OCMock to verify that a method is never called?

    - by Justin Voss
    At my day job I've been spoiled with Mockito's never() verification, which can confirm that a mock method is never called. Is there some way to accomplish the same thing using Objective-C and OCMock? I've been using the code below, which works but it feels like a hack. I'm hoping there's a better way... - (void)testSomeMethodIsNeverCalled { id mock = [OCMockObject mockForClass:[MyObject class]]; [[[mock stub] andCall:@selector(fail) onObject:self] forbiddenMethod]; // more test things here, which hopefully // never call [mock forbiddenMethod]... } - (void)fail { STFail(@"This method is forbidden!"); }

    Read the article

  • How to mock HTTPSession/FlexSession with TestNG and some Mocking Framework

    - by ifischer
    I'm developing a web application running on Tomcat 6, with Flex as Frontend. I'm testing my backend with TestNG. Currently, I'm trying to test the following method in my Java-Backend: public UserPE login(String mail, String password) { UserPE dbuser = findUserByMail(mail); if (dbuser == null || !dbuser.getPassword().equals(password)) throw new RuntimeException("Invalid username and/or password"); // Save logged in user FlexSession session = FlexContext.getFlexSession(); session.setAttribute("user", dbuser); return dbuser; } The method needs access to the FlexContext which only exists when i run it on the Servlet container (don't bother if you don't know Flex, it's more a Java-Mocking question in general). Otherwise i get a Nullpointer exception when calling session.setAttribute(). Unfortunately, I cannot set the FlexContext from outside, which would make me able to set it from my tests. It's just obtained inside the method. What would be the best way to test this method with a Mocking framework, without changing the method or the class which includes the method? And which framework would be the easiest for this use case (there are hardly other things i have to mock in my app, it's pretty simple)? Sorry I could try out all of them for myself and see how i could get this to work, but i hope that i'll get a quickstart with some good advices!

    Read the article

  • How to test IO code in JUnit?

    - by add
    I'm want to test two services: service which builds file name service which writes some data into file provided by 1st service In first i'm building some complex file structure (just for example {user}/{date}/{time}/{generatedId}.bin) In second i'm writing data to the file passed by first service (1st service calls 2nd service) How can I test both services using mocks without making any real IO interractions? Just for example: 1st service: public class DefaultLogService implements LogService { public void log(SomeComplexData data) { serializer.write(new FileOutputStream(buildComplexFileStructure()), data); or serializer.write(buildComplexFileStructure(), data); or serializer.write(new GenericInputEntity(buildComplexFileStructure()), data); } private ComplextDataSerializer serializer; // mocked in tests } 2nd service: public class DefaultComplexDataSerializer implements ComplexDataSerializer { void write(InputStream stream, SomeComplexData data) {...} or void write(File file, SomeCompexData data) {...} or void write(GenericInputEntity entity, SomeComplexData data) {...} } In first case i need to pass FileOutputStream which will create a file (i.e. i can't test 1st service) In second case i need to pass File. What can i do in 2nd service test if I need to test data which will be written to specified file? (i can't test 2nd service) In third case i think i need some generic IO object which will wrap File. Maybe there is some ready-to-use solution for this purpose?

    Read the article

  • How to let the matcher to match the second invocation on mock?

    - by Alex Luya
    I have an interface like this public interface EventBus{ public void fireEvent(GwtEvent<?> event); } and test code(testng method) looks like this: @Test public void testFireEvent(){ EventBus mock=mock(EventBus.class); //when both Event1 and Event2 are subclasses of GwtEvent<?> mock.fireEvent(new Event1()); mock.fireEvent(new Event2()); //then verify(mock).fireEvent(argThat(new Event2Matcher())); } Event2Matcher looks like this: private class Event2Matcher extends ArgumentMatcher<Event2> { @Override public boolean matches(Object arg) { return ((Event2) arg).getSth==sth; } } But get an error indicating that: Event1 can't be cast to Event2 And obviously,the matcher matched the first invoking mock.fireEvent(new Event1()); So,the statement within matcher return ((Event2) arg).getSth==sth; Will throw out this exception.So the question is how to let verify(mock).fireEvent(argThat(new Event2Matcher())); to match the second invoking?

    Read the article

  • How to mock static member variables

    - by pkrish
    I have a class ClassToTest which has a dependency on ClassToMock. public class ClassToMock { private static final String MEMBER_1 = FileReader.readMemeber1(); protected void someMethod() { ... } } The unit test case for ClassToTest. public class ClassToTestTest { private ClassToMock _mock; @Before public void setUp() throws Exception { _mock = mock(ClassToMock.class) } } When mock is called in the setUp() method, FileReader.readMemeber1(); is executed. Is there a way to avoid this? I think one way is to initialize the MEMBER_1 inside a method. Any other alternatives? Thanks!

    Read the article

1 2  | Next Page >