Mockito when andReturn cannot return expected result - mockito

I m writing a unit test to test the controller. However, I tried to use Mockito when...andReturn(true) to make the function return true but I still cannot pass the test.
#Test
public void testingFunc() throws Exception{
Mockito.when(testingService.create(userId, deviceId, requestIP, userAgent,"test","test")).thenReturn(true);
MvcResult result = mockMvc.perform(post("/test")
.param("id","testing")
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
String response = result.getResponse().getContentAsString();
assertEquals("success", response);
}
#RequestMapping(method = RequestMethod.POST, value="/test")
#ResponseBody
public String response(String id){
boolean result = testingService.create(userId, Base64.encodeBase64URLSafeString(deviceId.getBytes()),
request.getRemoteAddr(), Base64.encodeBase64URLSafeString(userAgent.toString().getBytes(Charset.forName("UTF-8"))), "test", "test");
if(result) return "success";
return "fail";
}

Related

How to properly call GroovyScriptEngine?

I'm testing Groovy but I can't figure out how to properly call GroovyScriptEngine. It keeps producing an error below.
org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack
Song.Groovy
class Song {
def args;
{
println "Song has been called." + args;
}
String getArtist(){
return "sdfsdf";
}
public String toString(){
return "Hey!";
}
}
Java Main ->
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
Object s = "Default...";
binding.setVariable("args", s);
gse.run("Song.groovy", binding);
the args variable also produce null..
What to do ?
You are loading a class!
If you want to test your class, try something like this in the end of your Song.groovy:
// Instantiate an object of your class and use some methods!
def song = new Song()
println song.getArtist();
When you run
gse.run("Song.groovy", binding);
You are basically loading your class, but you are not doing anything with it.
See this example here
(Posted on behalf of the OP):
Working code:
Test1.java
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class Test1 {
public static void main(String[] args) throws Exception {
String[] paths = { "C:\\Users\\User\\workspace\\GroovyTest\\src\\groovy" };
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
binding.setVariable("args", "Test Data");
String result = (String) gse.run("File1.groovy", binding);
System.out.println("Groovy Result: " + result);
}
}
File1.groovy
package groovy;
class Greeter {
String sayHello(String data) {
def greet = data;
return greet
}
}
static void main(String[] args) {
def greeter = new Greeter()
return greeter.sayHello(args);
}

Why does Spock think my Data Provider has no data?

I just wrote my own data Provider, which should read a file in chunks and provides it to my spock specification.
While debugging the next() method returns a proper batch and the hasNext() returns false if the reader can not read any more lines.
But I get this exception: SpockExecutionException: Data provider has no data
Here is my Provider and my feature
class DumpProvider implements Iterable<ArrayList<String>> {
private File fileHandle
private BufferedReader fileReader
private ArrayList<String> currentBatch = new ArrayList<String>()
private int chunksize
private boolean hasNext = true
DumpProvider(String pathToFile, int chunksize) {
this.chunksize = chunksize
this.fileHandle = new File(pathToFile)
this.fileReader = this.fileHandle.newReader()
}
#Override
Iterator iterator() {
new Iterator<ArrayList<String>>() {
#Override
boolean hasNext() {
if (hasNext) {
String nextLine = fileReader.readLine()
if (nextLine != null) {
currentBatch.push(nextLine)
} else {
hasNext = false
fileReader.close()
fileHandle = null
}
}
return hasNext
}
#Override
ArrayList<String> next() {
(chunksize - currentBatch.size()).times {
String line = fileReader.readLine()
if (line != null) {
currentBatch.push(line)
}
}
def batch = new ArrayList<String>(currentBatch)
currentBatch = new ArrayList<String>()
return batch
}
#Override
void remove() {
throw new UnsupportedOperationException();
}
}
}
}
Spock Feature
def "small import"() {
when:
println 'test'
println profileJSONStrings
connector.insertMultiple(profileJSONStrings as ArrayList<String>)
then:
println "hello"
where:
profileJSONStrings << dataProvider
}

RhinoMocks AssertWasCalled throws Exception

I am new to TDD and RhinoMocks.
I am trying to test AssertWasCalled but having problems. The constructor to my test is as follows:
public AccountControllerTests()
{
_webAuthenticator = MockRepository.GenerateMock<IWebAuthenticator>();
}
And my test is like this:
[TestMethod]
public void AccountControllerCallsWebAuthenticator_CreateSignInTicketForGoodLoginCredentials()
{
const string username = "good-username";
const string password = "good-password";
var model = new LoginModel { Username = username, Password = password };
_webAuthenticator.Stub(w => w.Authenticate(username, password)).Return(true);
var mockHttpContextBase = MockRepository.GenerateMock<HttpContextBase>();
var accountController = new AccountController(_webAuthenticator);
accountController.Login(model);
_webAuthenticator.AssertWasCalled(x => x.CreateSignInTicket(mockHttpContextBase, username));
}
The error I get is:
Test method Paxium.Music.WebUI.Tests.Controllers.AccountControllerTests.AccountControllerCallsWebAuthenticator_CreateSignInTicketForGoodLoginCredentials threw exception:
Rhino.Mocks.Exceptions.ExpectationViolationException: IWebAuthenticator.CreateSignInTicket(Castle.Proxies.HttpContextBaseProxy7f274f09b6124e6da32d96dc6d3fface, "good-username"); Expected #1, Actual #0.
I have now changed my code as below - Before and after code:
Before:
public class AccountController : Controller
{
private readonly IWebAuthenticator _webAuthenticator;
public AccountController(IWebAuthenticator webAuthenticator)
{
_webAuthenticator = webAuthenticator;
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (_webAuthenticator.Authenticate(model.Username, model.Password))
{
_webAuthenticator.CreateSignInTicket(HttpContext, model.Username);
return RedirectToAction("Index", "Home");
}
return View(model);
}
return View(model);
}
}
After:
public class AccountController : Controller
{
private readonly IWebAuthenticator _webAuthenticator;
private readonly HttpContextBase _contextBase;
public AccountController()
{
}
public AccountController(IWebAuthenticator webAuthenticator, HttpContextBase contextBase)
{
_webAuthenticator = webAuthenticator;
_contextBase = contextBase;
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (_webAuthenticator.Authenticate(model.Username, model.Password))
{
_webAuthenticator.CreateSignInTicket(_contextBase, model.Username);
return RedirectToAction("Index", "Home");
}
return View(model);
}
return View(model);
}
}
My tests now pass. How I inject in the contextBase though when my controller is used for real?? I am using StructureMap.
The error message you are receiving indicates that the Assert failed, i.e. the webAuthenticator object was not called with those specific arguments (hence expected #1, actual #0 exception message).
From the limited context you provide, I suspect that the fake instance of the HttpContextBase (mockHttpContextBase) in your test is not the same object that's being passed to the webAuthenticator from your production code.
There's two ways you can go about this: make the assert less strict or make sure the production code uses the fake http context object. If you don't care which instance of HttpContext gets passed to the webAuthenticator in this test, you can use argument matchers (Rhinomocks calls them argument constraints).
In your case, this would turn out something like this:
_webAuthenticator.AssertWasCalled(x => x.CreateSignInTicket(Arg<HttpContextBase>.Is.Anything, Arg<string>.Is.Equal(username)));

Groovy skips JsonNode objects on checking for null even if they not null

Why Groovy skips this if statement?
public static void main(String[] args) {
JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
if (jsonNode) {
println 'It works' //doesn't print it
}
}
Explicit checking for null works well:
public static void main(String[] args) {
JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
if (jsonNode != null) {
println 'It works' //works well
}
}
Imports:
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.databind.node.ObjectNode
Also if I use breakpoints in Intellij it works.
It depends on Groovy Object#asBoolean.
By default it returns false if object is null.
asBoolean()
Coerce an object instance to a boolean value. An object is coerced to
true if it's not null, to false if it is null.
Groovy tries to cast object to boolean with asBoolean() when there is such check.
This example shows that:
public static void main(String[] args) {
AsBoolFalse asBoolFalse = new AsBoolFalse()
if (asBoolFalse) {
println 'AsBoolFalse doesn\'t work' //doesn't print it
}
AsBoolTrue asBoolTrue = new AsBoolTrue()
if (asBoolTrue) {
println 'AsBoolTrue works' //works well
}
}
static class AsBoolFalse {
public boolean asBoolean() {
return false
}
}
static class AsBoolTrue {
public boolean asBoolean() {
return true
}
}
JsonNode overrides asBoolean() to return false, so we need explicit check for null.

reading an object from stream

I'm trying to read an object ChatMassage from the stream and to print a message (which this object contains) with its method getMassage(). It prints a message the first time but next time it always prints the first message. What is wrong?
Here is an example of the code:
while(keepGoing){
System.out.println("Client: " + ((ChatMassage) in.readObject()).getMassage() + "\n" );
}
ChatMassage class:
public class ChatMassage implements Serializable {
String msg, recipientName = null;
String senderName = "None";
public void setMassage(String msg) {
this.msg = msg;
}
public void setRecipientName(String recName) {
recipientName = recName;
}
public String getMassage() {
return msg;
}
public String getRecipientName() {
return recipientName;
}
public void setSenderName(String name) {
senderName = name;
}
public String getSenderName() {
return senderName;
}
}
I think the problem lies in this method:
public void setMassage(String msg) {
this.msg = msg;
}
I don't know if that can be a problem, but try changing the parameter to something like "new_msg". I think it confuses the "this.msg" with "msg".

Resources