I am trying to use Mockito to test my GWTP application.
I am trying to Mock my View,Proxy,Placemanager and eventbus.
I tried using
#Mock
AbcView abc;
and Abcview abc = Mockito.mock(AbcView.class);
However every time the mocked view is instantiated as null.
How shall i address the same?
Once the view is mocked i will be able go on with testing my presenter class, as the constructor of presenter has following code:
getView().setUiHandlers( this );
so until view is instantiated properly null pointer exception is thrown.
Did you run your test using the MockitoJUnitRunner runner?
#RunWith(MockitoJUnitRunner.class)
public class ExampleTest {
#Mock
private List list;
#Test
public void shouldDoSomething() {
list.add(100);
}
}
Besides #Sydney's response, you also need o make sure that AbcView.class is not final. I forget whether a final class results in a null or a runtime error, but that can be a cause for some sort of unexpected behavior -- one way or another, the mocking doesn't work. And if the class is not final, you need to make sure that any methods you stub on that mock are not final.
Related
I'm creating tests over existing classes. A number of them have a resource bundle defined as a private final field that's initialized when the object is created via new. I declare a mocked ResourceBundle, use PowerMock's mockStatic method to enable static mocking, and mock the getBundle method to return my mocked ResourceBundle. However, when the constructor runs the code to initialize the field, it simply creates the new resource bundle rather than using the mocked one. I feel like there's one little detail I've missed, but I don't know what it might be.
The reason all this is a problem is this: when I run the test locally, it creates the ResourceBundle object without issue. But when the test is run via our build software (UCBuild), it throws a "can't find resource" exception and the test, and therefore the build, fails.
When I run a test in debug and set a method breakpoint on the constructor, I can see that the "strings" object is created using an actual resource bundle, not the mocked one. I can't for the life of me figure out why.
I've tried declaring the field without initializing it, then using class.getDeclaredField() and Field.setAccesible() to set the resource bundle to point at my mocked one, but of course this just gets overwritten if I run code that re-initializes the field.
The WorkerTest class which tests Worker.java:
#RunWith(PowerMockRunner.class)
#PrepareForTest({FacesContext.class, SaveStatus.class, FacesMessage.class, ResourceBundle.class})
public class WorkerTest {
#Mock
private ResourceBundle mockRB;
#Before
public void setUp() throws Exception {
PowerMockito.mockStatic(ResourceBundle.class);
PowerMockito.when(ResourceBundle.getBundle(anyString())).thenReturn(mockRB);
PowerMockito.when(mockRB.getString(anyString())).thenReturn("tst");
sut = new Worker(); // Breakpoint here to verify mockRB exists
}
...some tests
}
Worker.java:
#Named
#ApplicationScoped
public class Worker implements Serializable {
private static final long serialVersionUID = 4075799125164038417L;
private final ResourceBundle strings = ResourceBundle
.getBundle("com.resources.strings");
public Worker() { //method breakpoint here
}
Thanks in advance
Found the problem. Adding Worker.class to the #PrepareForTest annotation line and everything worked fine.
I'm writing a unit test class (using testng) that has mocked member variables (using Mockito) and running the tests in parallel. I initially set up the expected mock in an #BeforeClass method, and in each test case I break something by creating a Mockito.when for each exceptional case.
What I'm seeing (unsurprisingly) is that these tests aren't independent; the Mockito.when in one test case affects the others. I noticed that I could be set up the mocks before each test, and I changed the #BeforeClass to #BeforeMethod. I still didn't expect these to pass consistently, as the tests are all still operating on the same shared mock object at the same time. However, all the tests started passing consistently. My question is "why"? Will this eventually fail? No matter what I do (Thread.sleep, etc) I can't reproduce a failure.
Is using #BeforeMethod enough to make these tests independent? If so, can anyone explain why?
Example code below:
public class ExampleTest {
#Mock
private List<String> list;
#BeforeClass // Changing to #BeforeMethod works for some reason
public void setup() throws NoSuchComponentException, ADPRuntimeException {
MockitoAnnotations.initMocks(this);
Mockito.when(list.get(0)).thenReturn("normal");
}
#Test
public void testNormalCase() throws InterruptedException {
assertEquals(list.get(0), "normal"); // Fails with expected [normal] but found [exceptional]
}
#Test
public void testExceptionalCase() throws InterruptedException {
Mockito.when(list.get(0)).thenReturn("exceptional");
assertEquals(list.get(0), "exceptional");
}
}
The problem here is that TestNG creates one instance of your test class ExampleTest and this is the instance that is used by both of your #Test methods.
So when you used #BeforeClass, you would have random failures with testNormalCase() if testExceptionalCase() ran first and altered the state of your test class.
When you changed your annotation to be #BeforeMethod, it would cause the setup to be executed right before every #Test method was executed.
So the setup would fix the state for testNormalCase() which is why it would pass, and since testExceptionalCase() was internally altering the state using Mockito.when() and then running assertions, it would pass all the time as well.
But there's one scenario wherein your setup will still fail, viz., when you use parallel="methods" attribute in your <suite> tag within your TestNG suite xml file i.e., when you configure TestNG and instruct it to run every #Test method in parallel.
In that case, the Mockito.when() within testExceptionalCase() will affect the shared state [ since you are using this in a shared manner amongst all your #Test methods ] causing testNormalCase() to fail randomly.
To fix this, I would suggest that you do the following :
Don't share this between your #Test methods, but house it separately outside of your test class i.e., house all the data members of your test class in a separate pojo which would be mocked rather than mocking this.
Use a ThreadLocal to store the state which is being mocked by Mockito.when() and then run assertions on the ThreadLocal from within your #Test methods.
I have the following legacy class that I want to add some unit tests to using Xunit and Moq
The psuedo code for the class I want to test is below:-
public class Foo : IFoo
{
public StatusResposne GetStatus(string jobId)
{
.
.
var response = GetRequest(doc, targeturl);
.
.
}
private XDocument GetRequest(XDocument doc, string url)
{
}
}
Now i want to test GetStatus but im order to do that i need to mock the GetRequest method.
Can anyone suggest the easiest way to do this?
Cheers
Unit testing ought to be black-box testing, because otherwise your tests will be too brittle: every time you change an implementation detail, you'll need to fix all the tests that break.
When you view Foo as a black box, only GetStatus is visible. The fact that there's a private GetRequest method is irrelevant. Someone else might come by tomorrow and decide to refactor the GetStatus implementation in such a way that the GetRequest method is no longer used - perhaps that method will no longer be there.
You should test the observable behaviour of GetStatus, instead of attempting to test implementation details.
i need to mock the GetRequest method
That's not possible. You can only mock interfaces and accessible virtual methods.
Do you have access to the source code?
One way could be to make GetRequest protected virtual and override it in some inherited class and use this class for the unit tests.
Better would be to move this method to some other class and use it as a dependency.
I have an AuthenticationManager.authenticate(username,password) method that gets called in someMethod of a SomeService under test. The AuthenticationManager is injected into SomeService:
#Component
public class SomeService {
#Inject
private AuthenticationManager authenticationManager;
public void someMethod() {
authenticationManager.authenticate(username, password);
// do more stuff that I want to test
}
}
Now for the unit test I need the authenticate method to just pretend it worked correctly, in my case do nothing, so I can test if the method itself does the expected work (Authentication is tested elsewhere according to the unit testing principles, however authenticate needs to be called inside that method) So I am thinking, I need SomeService to use a mocked AuthenticationManager that will just return and do nothing else when authenticate() gets called by someMethod().
How do I do that with PowerMock (or EasyMock / Mockito, which are part of PowerMock)?
With Mockito you could just do that with this piece of code (using JUnit) :
#RunWith(MockitoJUnitRunner.class)
class SomeServiceTest {
#Mock AuthenitcationManager authenticationManager;
#InjectMocks SomeService testedService;
#Test public void the_expected_behavior() {
// given
// nothing, mock is already injected and won't do anything anyway
// or maybe set the username
// when
testService.someMethod
// then
verify(authenticationManager).authenticate(eq("user"), anyString())
}
}
And voila. If you want to have specific behavior, just use the stubbing syntax; see the documentation there.
Also please note that I used BDD keywords, which is a neat way to work / design your test and code while practicing Test Driven Development.
Hope that helps.
I'm trying to unit test a custom ValueResolver (Automapper) but am running into problems because the method it forces me to override is not exposed directly in the custom object we must create. I override the protected method "ResolveCore" but the only public method exposed is "Resolve" which expects a complex "ResolutionResult" automapper object as it's input. In the vein of true unit testing I want to test this object / method in isolation to anything else and don't really want to go the route of firing up automapper with mappings to do this test. Likewise it's not possible to Mock "ResolutionResult" and it seems a very complex object to setup for each test (again requiring creation / association of other Automapper objects).
The only (less than ideal) solution I can come up with (and have seen suggested when Googling for a solution) is to stub a public method inside the class that exposes the protected overriden method. If we must go down this route then so be it, but has anyone else got a better solution that tests the method call in isolation doesn't require a modification of the object we are trying to test?
Example code:
public class CustomResolver : ValueResolver<Supplier, string>
{
protected override string ResolveCore(Custom source)
{
return string.Format("{0} {1}", source.Name, source.Descripton);
}
public string UnitTestStub(Custom source)
{
return ResolveCore(source);
}
}
I wouldn't place a public stub in your class. Instead, I'd just create a simple subclass in my unit test assembly that exposes the call I wanted to test:
public class TestCustomResolver : CustomResolver
{
public string TestResolveCore(Custom source)
{
return this.ResolveCore(source);
}
}
Some of this depends on the unit testing framework you're using too. For example, you could use the InternalsVisibleTo() attribute to expose your internals to your unit tests. However, I would lean towards a simple subclass in your unit tests.